放大画布后限制图像上的拖动

时间:2017-09-08 09:43:52

标签: javascript jquery html5 canvas drag

过去几天我一直在玩帆布,虽然我已经完成了大部分我想做的事情,但我正在努力解决一个问题。我可以加载,缩放和放大移动图像没有问题。

但是,在画布元素中缩放图像后,我希望能够拖动该图像,但是限制拖动,使得缩放图像的右边缘不能移动到画布的右边缘之外,缩放图像的左边缘,从不超出画布的左边缘等

我想要达到的效果正是在plunker中产生的效果。

canvas.on('object:moving', function(e) {

    var obj;
    obj = e.target;
    obj.setCoords();

    var boundingRect = obj.getBoundingRect();
    var zoom = canvas.getZoom();
    var viewportMatrix = canvas.viewportTransform;

    //there is a bug in fabric that causes bounding rects to not be 
    transformed by viewport matrix
    //this code should compensate for the bug for now

    boundingRect.top = (boundingRect.top - viewportMatrix[5]) / zoom;
    boundingRect.left = (boundingRect.left - viewportMatrix[4]) / zoom;
    boundingRect.width /= zoom;
    boundingRect.height /= zoom;


    // if object is too big ignore

    if (obj.currentHeight * zoom > obj.canvas.height * zoom || obj.currentWidth * zoom > obj.canvas.width * zoom) {
        return;
    }

    var canvasHeight = obj.canvas.height / zoom,
    canvasWidth = obj.canvas.width / zoom,
    rTop = boundingRect.top + boundingRect.height,
    rLeft = boundingRect.left + boundingRect.width;

    // top-left  corner
    if (rTop < canvasHeight || rLeft < canvasWidth) {
        obj.top = Math.max(obj.top, canvasHeight - boundingRect.height);
        obj.left = Math.max(obj.left, canvasWidth - boundingRect.width);
    }


    // bot-right corner
    if (boundingRect.top + boundingRect.height > obj.canvas.height || boundingRect.left + boundingRect.width > obj.canvas.width) {

        obj.top = Math.min(obj.top, obj.canvas.height - boundingRect.height + obj.top - boundingRect.top);
        obj.left = Math.min(obj.left, obj.canvas.width - boundingRect.width + obj.left - boundingRect.left);
    }
    //canvas.sendToBack(canvas.getObjects()[0])
}

但是我没有使用fabric js。 Here is a fiddle with the code I am using

任何帮助我如何实现这一点将不胜感激! 感谢

0 个答案:

没有答案