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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With