How to draw a line at a specific Angle using Canvas and Javascript

When looking at how to draw a line at a specific angle on a Canvas Element using Javascript,  I couldn’t find anything that was really short and sweet (really I just wanted a copy and paste),  I had to investigate the maths abit todo it and understand it, but I won’t go into that here.

So if you just want to draw a line at a specific angle on a Canvas HTML using Javascript, here it is.

Just plugin in the relevant values to the javascript function below to draw your Line on the Canvas ( starting position x and y, line length, angle, and canvas context).

var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");

var startingXPosition = myCanvas.width/2;  // center of canvas
var startingYPosition = myCanvas.height/2; // center of canvas
var angle = 45; // angle of line to draw at relative to default starting angle
var length = 50; 

lineAtAngle(startingXPosition, startingYPosition, length, angle, ctx); 

function lineAtAngle(x1, y1, length, angle, canvas) {    
    canvas.moveTo(x1, y1);  
    radians = angle * (Math.PI/180);     
    x2 = x1 + Math.cos(radians ) * length;	 
    y2 = y1 + Math.sin(radians ) * length;	   
    canvas.lineTo(x2, y2);       


Leave a Comment