简体   繁体   中英

scaling fabric js canvas with all its objects

i am using a function to scale entire fabric.js canvas, this function takes value in percentage like zoomCanvas(2.2); where 2.2 means 220% but instead of percentage i need to scale canvas by pixels to fit canvas in container for example when canvas is loaded on a page from json data its initial size is like 1200px x 700px and my container size is 500px. now i need to find a way by which can convert this 500px to a percentage value so that entire canvas and all its object fits in 500px.

This is scaling function where factor is percent value

   function zoomCanvas(factor) {
canvas.setHeight(canvas.getHeight() * factor);
canvas.setWidth(canvas.getWidth() * factor);
if (canvas.backgroundImage) {
    // Need to scale background images as well
    var bi = canvas.backgroundImage;
    bi.width = bi.width * factor; bi.height = bi.height * factor;
}
var objects = canvas.getObjects();



var tcounter = 0;

for (var i in objects) {

    tcounter++;


    //alert(tcounter);
    var scaleX = objects[i].scaleX;
    var scaleY = objects[i].scaleY;
    var left = objects[i].left;
    var top = objects[i].top;

    var tempScaleX = scaleX * factor;
    var tempScaleY = scaleY * factor;
    var tempLeft = left * factor;
    var tempTop = top * factor;

    objects[i].scaleX = tempScaleX;
    objects[i].scaleY = tempScaleY;
    objects[i].left = tempLeft;
    objects[i].top = tempTop;

    objects[i].setCoords();
}
canvas.renderAll();
canvas.calcOffset();
}

The scale factor you need is:

scaleRatio = Math.min(containerWidth/canvasWidth, containerHeight/canvasHeight);

To zoom your canvas you should really just use:

canvas.setDimensions({ width: canvas.getWidth() * scaleRatio, height: canvas.getHeight() * scaleRatio });

then

canvas.setZoom(scaleRatio)

A custom zoom function should not be needed

You should have an original canvas with some dimensions. From that canvas you should just find yours factorX and factorY values. For example, your original canvas is 1280x1020 px and you need to convert to the dimension 500x500px.

var factorX = 500 / 1280;
var factorY = 500 / 1020;

Than, modify your function from

function zoomCanvas(factor) {...}

to

function zoomCanvas(factorX, factorY) {...}

Use factorX for width values, and factorY for height values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM