Drag and Drop on Canvas
This article will help you to implement drag and drop features on canvas element. First of all we need one canvas element
<canvas id=”deepCan” width=”400" height=”300">
Drag and drop is handled in three phases:
- Detect a mousedown event over a shape, which begins the operation
function doMouseDown(e){
if (e.pageX < x + 30 + can.offsetLeft && e.pageX > x — 30 +
can.offsetLeft && e.pageY < y + 30 + can.offsetTop &&
e.pageY > y -30 + can.offsetTop){
x = e.pageX — can.offsetLeft;
y = e.pageY — can.offsetTop;
dragok = true;
can.onmousemove = doMouseMove;
}
}
2. Position the shape according to the mouse coordinates using the mousemove event listener
function doMouseMove(e){
if (dragok){
x = e.pageX — can.offsetLeft;
y = e.pageY — can.offsetTop;
}
}
3. Drop the shape when the mouse button is released (mouseup)
function doMouseUp(){
dragok = false;
can.onmousemove = null;
}
Please get the complete source code from below location