HTML5 Canvas moving object to mouse click position

后端 未结 1 717
無奈伤痛
無奈伤痛 2020-12-10 19:04

Basically I want to move an object from point A ( 10x,10y ) to a position on the canvas where the mouse has been clicked ( 255x,34y ).

I\'m currently using a method

1条回答
  •  感情败类
    2020-12-10 19:59

    When you “move” an object, what you really need to do is erase the object and redraw it

    First code a function that will redraw the rect at a specified x,y

    function draw(x,y){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.beginPath();
        ctx.fillStyle="skyblue";
        ctx.strokeStyle="gray";
        ctx.rect(x,y,30,20);
        ctx.fill();
        ctx.stroke();
    }
    

    Then handle mousedown events and call the draw function

    This example uses jquery for cross-browser compatibility, but you can always recode using native javascript.

    // listen for all mousedown events on the canvas
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    
    
    // handle the mousedown event
    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#downlog").html("Down: "+ mouseX + " / " + mouseY);
    
      // Put your mousedown stuff here
      draw(mouseX,mouseY);
    }
    

    Here is code and a Fiddle: http://jsfiddle.net/m1erickson/GHSG4/

    
    
    
     
    
    
    
    
    
    
    
    
    
        

    Click to redraw the rect at the mouse position

    Down

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