Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need background image stretch to cover the whole canvas in fabricjs

Tags:

fabricjs

i can upload the background image. but i don't kmow how strech to cover the whole canvas. sample code

var fr = new FileReader;
fr.onload = function() {
    var image = new Image();
    image.onload = function() {
        var imgwidth = this.width;
        currentcanvas.setBackgroundImage(fr.result, currentcanvas.renderAll.bind(currentcanvas), {

          scaleX: currentcanvas.width / imgwidth,
            scaleY: currentcanvas.height / imgwidth
        });
        currentcanvas.renderAll();
    };
like image 428
durai pandiyank Avatar asked Nov 27 '25 05:11

durai pandiyank


2 Answers

In fabricjs 2.x, things are very different. Here's the code to stretch a background image to canvas size for fabricjs 2.x:

// Assume fcanvas is fabricjs canvas:
fabric.Image.fromURL('background.png', function(img){
   img.scaleToWidth(fcanvas.width);
   img.scaleToHeight(fcanvas.height);
   fcanvas.setBackgroundImage(img);
   fcanvas.requestRenderAll();
});
like image 168
av01d Avatar answered Nov 28 '25 19:11

av01d


You can give background image's height and width according to canvas height and width as follow :

canvas.backgroundImage.width = canvas.getWidth();
canvas.backgroundImage.height = canvas.getHeight();
like image 33
Innodel Avatar answered Nov 28 '25 19:11

Innodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!