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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With