【发布时间】:2018-06-24 08:31:42
【问题描述】:
我正在尝试仅在画布内限制对象的移动。这是我通过以下代码实现的
if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left< 0){
obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left));
}
// bot-right corner
if(obj.getBoundingRect().top+obj.getBoundingRect().height > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width > obj.canvas.width){
obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
}
当我没有对画布应用缩放时,这很有效。 当我应用缩放 + 或缩放时,我也需要能够使其工作 -
我曾想过尝试这样解决它
if(obj.getBoundingRect().top*canvas.getZoom() < 0 || obj.getBoundingRect().left*canvas.getZoom() < 0){
obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top)*canvas.getZoom();
obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left)*canvas.getZoom();
}
// bot-right corner
if(obj.getBoundingRect().top*canvas.getZoom()+obj.getBoundingRect().height > obj.canvas.height || obj.getBoundingRect().left*canvas.getZoom()+obj.getBoundingRect().width > obj.canvas.width){
obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top)*canvas.getZoom();
obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left)*canvas.getZoom();
}
但它不起作用。你能帮帮我吗?
编辑:添加小提琴
https://jsfiddle.net/samael205/m19cuk0j/1/
编辑:Sloved,仅适用于 Fabric 2.0.0+
if(obj.getBoundingRect(true).top < 0 || obj.getBoundingRect(true).left < 0){
obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect(true).top);
obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect(true).left);
}
// bot-right corner
if(obj.getBoundingRect(true).top+obj.getBoundingRect(true).height > obj.canvas.height/canvas.getZoom() || obj.getBoundingRect(true).left+obj.getBoundingRect(true).width > obj.canvas.width/canvas.getZoom()){
obj.top = Math.min(obj.top, obj.canvas.height/canvas.getZoom()-obj.getBoundingRect(true).height+obj.top-obj.getBoundingRect(true).top);
obj.left = Math.min(obj.left, obj.canvas.width/canvas.getZoom()-obj.getBoundingRect(true).width+obj.left-obj.getBoundingRect(true).left);
}
【问题讨论】:
标签: javascript html canvas fabricjs