Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - Fit the background image to canvas size with Fabric js

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 implemented the stretching code.

Strech the background image to canvas size with Fabric.js
http://fabricjs.com/docs/fabric.Canvas.html#setBackgroundImage

Code

$(function () {     
    var canvas1 = new fabric.Canvas('canvas1');
            //Default
    var canvas = canvas1;

    //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) {
                img.set({
                    width: canvas.getWidth(), 
                    height: canvas.getHeight(), 
                    originX: 'left', 
                    originY: 'top'
                });
                canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
                /*canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
                    width: canvas.getWidth(),
                    height: canvas.getHeight(),
                    originX: 'left',
                    originY: 'top',
                    crossOrigin: 'anonymous'
                });*/
            });
        };
        reader.readAsDataURL(file);
    });
});

It seems that it is not working with latest beta version, however its working with 1.7.19 version but not with 2.0.0-beta.7

JSFiddle: version 2.0.0-beta.7: http://jsfiddle.net/dhavalsisodiya/8vLo882n/3

varsion 1.7.19: http://jsfiddle.net/dhavalsisodiya/8vLo882n/4/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...