Move an object in the direction of the "onmousemove"

Asked

Viewed 584 times

1

I’m trying to move an object in the direction where the person presses the screen, moves and then lets go. I tried to use some loops for (was the only thing I thought of) but without success.

[if you didn’t get it right follow the image of how it would be]Como é pra ser

I’m using HTML5 and Javascript canvas.

EDITED

My code so far

<!DOCTYPE html>
<html>
<head>
	<title>Canvas</title>
</head>
<body>
	<center>
		<canvas id="canvas" width="320" height="482"></canvas>
	</center>
	<script>
		var canvas   = document.getElementById("canvas");
		var contexto = canvas.getContext("2d");
		var touchX, touchY;
		var objetos = [];

		setInterval(function(){
			atualizaCanvas();
			atualizaPos();
		}, 25);

		function atualizaCanvas(){
			contexto.fillStyle = "#f0f0f0";
			contexto.fillRect(0, 0, 320, 482);
			for(var x in objetos){
				contexto.fillStyle = objetos[x].cor;
				contexto.fillRect(objetos[x].x, objetos[x].y, 20, 20);
			}
		}

		function atualizaPos(){
			for(var x in objetos){
				if(objetos[x].xComeco != objetos[x].xFinal){
					objetos[x].x += (objetos[x].xFinal - objetos[x].xComeco)/10;
				}
				objetos[x].y -= 10;
				if (objetos[x].y <= -10){
					delete objetos[x];
				}
			}
		}

		canvas.onmousedown = function(evento){
			touchX = evento.clientX - canvas.offsetLeft;
			touchY = evento.clientY - canvas.offsetTop;
		};

		canvas.onmouseup = function(evento){
			var ttX = evento.clientX - canvas.offsetLeft;
			var ttY = evento.clientY - canvas.offsetTop;
			if (ttY < touchY){
				objetos.push({
					x: touchX,
					y: touchY,
					cor: "red",
					xComeco: touchX,
					xFinal: ttX
				});
			}
		};
	</script>
</body>
</html>

  • You can show the code of what you’ve already started doing?

  • Show me your code, please. In general, if you want an animation to happen on a canvas without user interaction (i.e. the object keeps moving after point B) you should probably use getAnimationFrame. Or at most one setTimeout or setInterval. This part you already know how to do, or do you doubt it? So the question doesn’t get too wide, better contextualize, tell what you know how to do and what’s still bringing you trouble.

  • I’ve been trying a little harder and I’ve arrived at a code that even comes close to the expected for(var x in objetos){... objetos[x].x += (objetos[x].xFinal - objetos[x].xComeco)/10; ..., xComeco is the X position where the person started pressing the screen and xFinal is the X position where the person stopped pressing.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.