Scale fabric.js canvas objects
Asked Answered
A

2

16

I have a fabric.js canvas on my page, that I'd like to be responsive. My code works for scaling the canvas itself, but not the objects I've drawn on it. Any idea? I've searched SO but couldn't find a solution that worked for me.

var resizeCanvas;

resizeCanvas = function() {
  var height, ratio, width;
  ratio = 800 / 1177;
  width = tmpl.$('.canvas-wrapper').width();
  height = width / ratio;

  canvas.setDimensions({
    width: width,
    height: height
  });
};

Meteor.setTimeout(function() {
  return resizeCanvas();
}, 100);

$(window).resize(resizeCanvas);
Amass answered 3/2, 2015 at 14:26 Comment(0)
E
41

Here's my zoom function - We zoom the canvas, and then loop over all objects and scale them as well.

Call like zoomIt(2.2)

function zoomIt(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();
for (var i in objects) {
    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();
}
Earthshaking answered 3/2, 2015 at 14:59 Comment(7)
in this zoom factor is ratio or some thing else ?Frascati
Percentage. In the example, 2.2 would be 220% of original.Earthshaking
@Amass Can you post how you used this function in conjunction with the resize event? This function takes a scale factor - how did you get that from the resize event?Mccormack
@MichaelBates Old code, but it might be enough to get an idea: gist.github.com/zimt28/b33229fdb9559b01803cAmass
@JasonMaggard: if I do scalling 220% then again I do 150% then objects still increasing scalling because objects[i].scaleX it will give 2.2 and based on that scalling is increasing where it should scale with lower value.Deniable
Piyush, this is now supported directly by Fabric.js. You can zoom the canvas using built in APIs. I wouldn't use this if I were you.Earthshaking
If you were looking at making objects within objects responsive, I just figured it out here: #58720214Haemoglobin
S
1

For those looking for a fabric build-in method for scaling (aka zooming) a canvas, check out setZoom.

Shark answered 21/1, 2022 at 20:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.