使用缩放应用在画布画布边界限制内移动objecj

时间:2018-01-15 17:02:01

标签: javascript html5 canvas fabricjs

我试图仅在画布内限制对象的移动。这是我用以下代码实现的

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/

编辑:已解决,仅适用于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);
}

1 个答案:

答案 0 :(得分:0)

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

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