Canvas Curves

Angles Made Easy

Most games I've made involve drawing lines between two points in the plane, like how the canvas below shows an arrow pointing to your cursor.

Cursor Coordinates

cursor : (,)
var ctx; var theta; var x = 0; var y = 0; function cursormove(e){ x = e.pageX; y = e.pageY; $("#cursor_x").html(x); $("#cursor_y").html(y); drawAll(); } //for desktop document.addEventListener("mousemove", cursormove, false); //for mobile document.addEventListener("touchmove", cursormove, false); document.addEventListener("touchstart", cursormove, false);

Using the Angle

	
ctx = document.getElementById("arrow1").getContext("2d");
ctx.clearRect(0,0,100,100)
theta = Math.atan2(x - ($("#arrow1").position().left+50),y - ($("#arrow1").position().top+50));
ctx.beginPath();
ctx.lineWidth = 2;
ctx.moveTo(50,50);
ctx.lineTo(50 + 40*Math.sin(theta), 50 + 40*Math.cos(theta));
ctx.stroke();
if(theta < 0){
	theta += Math.PI*2;
}
ctx.fillText(theta,10,10);
	

Using canvas without Math

	
ctx = document.getElementById("arrow2").getContext("2d");
ctx.clearRect(0,0,100,100);
ctx.save();
theta = Math.atan2(x - ($("#arrow2").position().left+50),y - ($("#arrow2").position().top+50));
ctx.beginPath();
ctx.lineWidth = 2;
ctx.translate(50,50);
ctx.rotate(-theta);
ctx.moveTo(0,0);
ctx.lineTo(0,40);
ctx.stroke();
ctx.restore();		
	


`