Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
Valex Avatar asked Jul 01 '16 09:07

Valex


1 Answers

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.

like image 162
Incredibly HandSome Samuel Avatar answered Oct 29 '22 12:10

Incredibly HandSome Samuel