How to make HTML5 draggable objects over canvas?

后端 未结 1 1093
别那么骄傲
别那么骄傲 2021-02-10 09:35

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

1条回答
  •  温柔的废话
    2021-02-10 10:04

    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:

    • save this mouseX position in a variable (lastX)
    • save this mouseY position in a variable (lastY)
    • set the mouseIsDown flag to true

    On mouseUp

    • set the mouseIsDown flag to false

    On mouseMove

    • Hit-test each ship to see if it should be dragged.
    • If the lastX/lastY was inside a ship, that ship is being dragged
    • Move dragging ships by the distance the mouse has just moved

    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:

    • define a path (but not draw it -- no fill, no stroke)
    • use 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:

    • In production, you'll want to have the mouseMove just save the mouse positions.
    • Then have another procedure retrieve those saved positions and do hit-testing/redrawing.
    • That other procedure will probably be inside a timed loop like requestAnimationFrame.

    Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/sEBAC/

    
    
    
     
    
    
    
    
    
    
    
    
    
        
    
    
    

    0 讨论(0)
提交回复
热议问题