HTML5 Canvas moving an object to mouse position

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

I am currently using a method, but it comes from ++ X, then ++ Y to the coordinates; then on the right.

I want him to go directly to the position, he loves the animation along the way. Slowdown from point A to point B.

+4
source share
1 answer

When you “move” an object, you really need to delete the object and redraw it.

First, enter a function that will redraw the rectangle with the given 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 the mousedown events and call the draw function

This example uses jquery to be compatible with multiple browsers, but you can always transcode it using the built-in 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 the code and script: http://jsfiddle.net/m1erickson/GHSG4/

 <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <style> body{ background-color: ivory; } canvas{border:1px solid red;} </style> <script> $(function(){ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var canvasOffset=$("#canvas").offset(); var offsetX=canvasOffset.left; var offsetY=canvasOffset.top; 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(); } 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); } $("#canvas").mousedown(function(e){handleMouseDown(e);}); // start the rect at [10,10] draw(10,10); }); // end $(function(){}); </script> </head> <body> <p>Click to redraw the rect at the mouse position</p> <p id="downlog">Down</p> <canvas id="canvas" width=300 height=300></canvas> </body> </html> 
+11
source

Source: https://habr.com/ru/post/1482783/


All Articles