Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  27] [ 7]  / answers: 1 / hits: 24331  / 10 Years ago, tue, february 3, 2015, 12:00:00

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);

More From » canvas

 Answers
9

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();
}

[#67969] Sunday, February 1, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aileent

Total Points: 556
Total Questions: 107
Total Answers: 101

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;