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?