Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center FabricJS canvas background image?

When adding a backgroundImage to a canvas using setBackgroundImage(), I haven't been able to find a way to center the background image. I need to center it to line it up with the centered paths in the canvas.

The docs http://fabricjs.com/docs/fabric.StaticCanvas.html#setBackgroundImage show various information, but don't seem to specify positioning of the background image in relation to the canvas.

    canvas.setOverlayImage('http://fabricjs.com/assets/honey_im_subtle.png',
        canvas.renderAll.bind(canvas), {
            scaleX:1,
            scaleY:1,
            top: 0,
            left: 0,
            originX: 'center',
            originY: 'center'
    });

This will center the image to the top left corner of the canvas. How do I now specify that the origination point on the canvas should be center/center instead of top/left?

Update: is there a method that will update dynamically if the canvas is resized? Was hoping to use percentage values for top and left, but that doesn't seem to work.

Thanks!

like image 254
mike.bronner Avatar asked Dec 20 '22 15:12

mike.bronner


1 Answers

I was able to find a solution that works, but will not update automatically if the canvas is resized:

var center = deviceCanvas.getCenter();
canvas.setOverlayImage('http://fabricjs.com/assets/honey_im_subtle.png',
    canvas.renderAll.bind(canvas), {
        scaleX:1,
        scaleY:1,
        top: center.top,
        left: center.left,
        originX: 'center',
        originY: 'center'
});
like image 82
mike.bronner Avatar answered Dec 24 '22 01:12

mike.bronner