gpt4 book ai didi

javascript - 使用缩放应用在 Canvas Canvas 边界限制内移动对象

转载 作者:可可西里 更新时间:2023-11-01 13:44:13 28 4
gpt4 key购买 nike

我试图将对象的移动限制在 Canvas 内。这是我用下面的代码实现的

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

当我没有对 Canvas 应用缩放时,这很有效。当我应用 zoom + 或 zoom - 时,我也需要能够让它工作

我曾经想过这样解决

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

但它不起作用。你能帮帮我吗?

编辑:添加 fiddle

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

最佳答案

谢谢,一切正常,我重写了一点,对某人有用吗

canvas.on("object:moving", function(e){
var obj = e.target;
obj.setCoords();

var bound = obj.getBoundingRect(true);
var width = obj.canvas.width;
var height = obj.canvas.height;

obj.left = Math.min(Math.max(0, bound.left), width - bound.width);
obj.top = Math.min(Math.max(0, bound.top), height - bound.height);
})

关于javascript - 使用缩放应用在 Canvas Canvas 边界限制内移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48267587/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com