I just started learning html5 and I am trying to create a battleship interface with draggable ships. I need help making my dragging methods work. I am purposely not using a libr
This is the procedure for making an html shape draggable
Note that this has been answered before on SO (many times!)
But this answer illustrates the new context.isPointInPath method to hit-test whether a point is inside an html canvas path.
Hopefully, this new hit-testing method will be new & useful to the OP and others :)
Here's the general procedure for dragging shapes in html canvas:
On mouseDown:
On mouseUp
On mouseMove
MouseDown handler code:
function handleMouseDown(e){
// get the current mouse position relative to the canvas
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// save this last mouseX/mouseY
lastX=mouseX;
lastY=mouseY;
// set the mouseIsDown flag
mouseIsDown=true;
}
MouseUp handler code:
function handleMouseUp(e){
// clear the mouseIsDown flag
mouseIsDown=false;
}
MouseMove handler code:
This code illustrates using context.isPointInPath
to hit-test an html canvas path
The procedure to do that is:
context.isPointInPath(x,y)
to test if x,y are inside the path defined above.Here's the mouseMove handler using context.isPointInPath
function handleMouseMove(e){
// if the mouseIsDown flag is’nt set, no work to do
if(!mouseIsDown){ return; }
// get mouseX/mouseY
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// for each ship in the ships array
// use context.isPointInPath to test if it’s being dragged
for(var i=0;i
Note about enhancing performance:
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/sEBAC/