将裁剪框保留在其父容器中

时间:2019-01-31 12:29:05

标签: javascript

我为我的图像编辑器项目创建了一个裁剪框,并嵌入了拖动功能,但问题是,它不仅仅局限于其父容器,下面是代码

function dragCropBox(){

    let dragItem = document.querySelector("#image-editor-modal #crop-box");
    let container = document.querySelector('#image-editor-modal #image-editor-canvas #canvas-holder');

    let active = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;

    container.addEventListener("touchstart", dragStart, false);
    container.addEventListener("touchend", dragEnd, false);
    container.addEventListener("touchmove", drag, false);

    container.addEventListener("mousedown", dragStart, false);
    container.addEventListener("mouseup", dragEnd, false);
    container.addEventListener("mousemove", drag, false);


    function dragStart(e) {
      if (e.type === "touchstart") {
        initialX = e.touches[0].clientX - xOffset;
        initialY = e.touches[0].clientY - yOffset;
      } else {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;
      }

      if (e.target === dragItem) {
        active = true;
      }

    }

    function dragEnd(e) {
      initialX = currentX;
      initialY = currentY;

      active = false;
    }

    function drag(e) {
      if (active) {

        e.preventDefault();

        if (e.type === "touchmove") {
          currentX = e.touches[0].clientX - initialX;
          currentY = e.touches[0].clientY - initialY;
        } else {
          currentX = e.clientX - initialX;
          currentY = e.clientY - initialY;
        }

        xOffset = currentX;
        yOffset = currentY;

        setTranslate(currentX, currentY, dragItem);
      }
    }

    function setTranslate(xPos, yPos, el) {
      // el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
      el.style.top = yPos+'px';
      el.style.left = xPos+'px';
    }
}

有什么想法只限制在其父容器内拖动吗?

0 个答案:

没有答案