Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I resize a Fabric.js canvas and all the content inside?

Tags:

fabricjs

Hello I'm trying to resize a Fabric.js canvas element and proportionally the content inside it. I just increase the width and height of canvas area, but the content like image, text, etc. remain in its original size. How can i achieve this behavior.

Thanks.

like image 525
Álvaro Avatar asked Oct 15 '25 12:10

Álvaro


1 Answers

Use below function to resize canvas proportionally along with all the elements/objects. You can pass any width/size GetCanvasAtResoution(279); Hope this helps.

Link to working version of solution: jsfiddle.net/zsk7785t

    function GetCanvasAtResoution(newWidth)
    {
        if (canvas.width != newWidth) {
            var scaleMultiplier = newWidth / canvas.width;
            var objects = canvas.getObjects();
            for (var i in objects) {
                objects[i].scaleX = objects[i].scaleX * scaleMultiplier;
                objects[i].scaleY = objects[i].scaleY * scaleMultiplier;
                objects[i].left = objects[i].left * scaleMultiplier;
                objects[i].top = objects[i].top * scaleMultiplier;
                objects[i].setCoords();
            }
            var obj = canvas.backgroundImage;
            if(obj){
                obj.scaleX = obj.scaleX * scaleMultiplier;
                obj.scaleY = obj.scaleY * scaleMultiplier;
            }

            canvas.discardActiveObject();
            canvas.setWidth(canvas.getWidth() * scaleMultiplier);
            canvas.setHeight(canvas.getHeight() * scaleMultiplier);
            canvas.renderAll();
            canvas.calcOffset();
        }           
    }
like image 128
Ranjana Avatar answered Oct 19 '25 13:10

Ranjana



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!