Valex
Valex

Reputation: 1196

Canvas drag on mouse movement

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?

Upvotes: 9

Views: 13787

Answers (1)

user6360214
user6360214

Reputation:

The problem your code has is that each time you move the rectangle blablabla px relative to the dragStart position, 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.

Upvotes: 9

Related Questions