Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize background image of canvas - Fabricjs

I am using fabricjs to play around with canvas, and loading a image into it via javascript.

I have a function that resizes the canvas to make it responsive and as such would like to resize the background image that was loaded to fit the canvas too but keep the aspect ratio.

I have not found examples currently that meet my criteria and am hoping someone can assist.

Javascript

var canvas = new fabric.Canvas('drawing_layer');
 var img = new Image();
            img.onload = function () {
                canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas), {
                    originX: 'left',
                    originY: 'top',
                    left: 0,
                    top: 0
                });

// initially sets width of canvas to fit the image
                canvas.setDimensions({
                    width: img.width,
                    height: img.height
                });
            };
// below is a call to function that resizes the canvas
resizeCanvas();

//sets listener to resize event
            window.addEventListener('resize', resizeCanvas);
like image 591
Aeseir Avatar asked Oct 21 '25 17:10

Aeseir


1 Answers

Your resizeCanvas() should look like:

resizeCanvas(width, height) {
  canvas.backgroundImage.scaleToWidth(width);
  canvas.backgroundImage.scaleToHeight(height);
  canvas.setDimensions({width: width, height: height});
  canvas.renderAll();
}

And you should be ok.

like image 105
AndreaBogazzi Avatar answered Oct 23 '25 06:10

AndreaBogazzi



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!