Canvas drag on mouse movement

走远了吗. 提交于 2021-02-07 13:43:30

问题


I'm trying to build a canvas that i can drag using mouse movement. And I'm doing something wrong that i cannot understand cause seems to work at first and then there is like an incremental error that make the canvas move too fast.

Considering the following code,

window.onload = function() {
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext('2d');


  function draw() {
    context.fillRect(25, 25, 100, 100);
  }

  function clear() {
    context.clearRect(0, 0, canvas.width, canvas.height);
  }
  var drag = false;
  var dragStart;
  var dragEnd;
  draw()
  canvas.addEventListener('mousedown', function(event) {
    dragStart = {
      x: event.pageX - canvas.offsetLeft,
      y: event.pageY - canvas.offsetTop
    }

    drag = true;

  })

  canvas.addEventListener('mousemove', function(event) {
    if (drag) {
      dragEnd = {
        x: event.pageX - canvas.offsetLeft,
        y: event.pageY - canvas.offsetTop
      }
      context.translate(dragEnd.x - dragStart.x, dragEnd.y - dragStart.y);
      clear()
      draw()
    }

  })

}

live example on Plunker https://plnkr.co/edit/j8QCxwDzXJZN2DKszKwm.

Can someone help me to understand what piece I'm missing?


回答1:


Your code is having problem, because:

Each time you want to move the rectangle blablabla px relative to the dragStart position, yet the translate() method is not based on dragStart position, but your current position.

To fix this, you should add the following after calling the translate method:

dragStart = dragEnd;

So that your position is also based on current mouse position.



来源:https://stackoverflow.com/questions/38142308/canvas-drag-on-mouse-movement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!