Fit the background image to canvas size with Fabric js

后端 未结 2 799
时光取名叫无心
时光取名叫无心 2020-12-01 20:08

I am trying to stretch the background image so it can fit the canvas size. But its not working.

I have followed this question and based on comment i have implemente

2条回答
  •  感动是毒
    2020-12-01 20:54

    The solution given by @spankajd is almost there but still not 100% accurate (as you'll see the background image doesn't completely fit to the canvas).

    The proper solution to this problem is indeed to use the scaleX and scaleY property (which takes a number as scaling factor), as mentioned by @asturur on your submitted issue.

    However, in that case you won't need to set the width and height property of the image. Also, a better (and correct) way of setting those image properties is to pass them as options (argument) to the setBackgroundImage() method (this may resolve some performance issues), as such :

    canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
       scaleX: canvas.width / img.width,
       scaleY: canvas.height / img.height
    });
    

    ... instead of setting them for the image object separately.

    that being said, here is a complete working example :

    $(function() {
       var canvas1 = new fabric.Canvas('canvas1');
       //Default
       var canvas = canvas1;
       canvas.backgroundColor = '#34AD39';
       canvas.renderAll();
       //Change background using Image
       document.getElementById('bg_image').addEventListener('change', function(e) {
          canvas.setBackgroundColor('', canvas.renderAll.bind(canvas));
          canvas.setBackgroundImage(0, canvas.renderAll.bind(canvas));
          var file = e.target.files[0];
          var reader = new FileReader();
          reader.onload = function(f) {
             var data = f.target.result;
             fabric.Image.fromURL(data, function(img) {
                canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
                   scaleX: canvas.width / img.width,
                   scaleY: canvas.height / img.height
                });
             });
          };
          reader.readAsDataURL(file);
       });
    });
    
    
    

提交回复
热议问题