gpt4 book ai didi

javascript - 在 Canvas 边界限制内移动对象

转载 作者:行者123 更新时间:2023-12-03 10:32:31 25 4
gpt4 key购买 nike

我试图限制 Canvas 内的移动对象,但是在顶部和左侧的限制区域中移动对象时遇到了一些困难,当我将对象缩放得更大时,我也无法限制左侧的移动对象和 Canvas 的顶部

canvas.observe("object:moving", function(e) {
var obj = e.target;
// if object is too big ignore
if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width) {
return;
}

var halfw = obj.currentWidth/2;
var halfh = obj.currentHeight/2;
var bounds = {
tl: {x: halfw, y:halfh},
br: {x: obj.canvas.width-halfw, y: obj.canvas.height-halfh}
};

// top-left corner
if(obj.top < bounds.tl.y || obj.left < bounds.tl.x) {
obj.top = Math.max(obj.top, bounds.tl.y);
obj.left = Math.max(obj.left, bounds.tl.x )
}

// bot-right corner
if(obj.top > bounds.br.y || obj.left > bounds.br.x) {
obj.top = Math.min(obj.top, bounds.br.y);
obj.left = Math.min(obj.left, bounds.br.x)
}
});

最佳答案

canvas.on('object:moving', function (e) {
var obj = e.target;
// if object is too big ignore
if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
return;
}
obj.setCoords();
// top-left corner
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);
}
});

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

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