Fit the background image to canvas size with Fabric js

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);
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-beta.7/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="margin-top:20px;">
   <label class="control-label">Add Background Image</label>
   <input type="file" id="bg_image" />
</div>

<canvas id="canvas1" width="600" height="400" style="border:1px solid #000"></canvas>

Leave a Comment