Reputation: 167
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.
Upvotes: 3
Views: 4017
Reputation: 815
Use below function to resize canvas proportionally along with all the elements/objects. You can pass any width/size GetCanvasAtResoution(279);
Hope this helps.
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();
}
}
Upvotes: 17