javascript 缩放 fabric.js 画布对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28301286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scale fabric.js canvas objects
提问by zimt28
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.
我的页面上有一个fabric.js 画布,我想要响应。我的代码适用于缩放画布本身,但不适用于我在其上绘制的对象。任何的想法?我已经搜索过,但找不到对我有用的解决方案。
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);
回答by Jason Maggard
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)
呼叫喜欢 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();
}