johnny
johnny

Reputation: 19735

How can I draw a line with lineTo in HTML5 that has angles to match the Unit Circle?

If I have this,

    var canvas = document.getElementById("my-canvas");  
    var ctx = canvas.getContext("2d");  

    ctx.fillStyle = '#f00';
    ctx.beginPath();
    ctx.moveTo(25, 25);
    ctx.lineTo(150, 25);
    ctx.rotate(Math.PI*7/4);  //315 degrees
    ctx.lineTo(150,90);

    ctx.stroke();

It does not draw the line (the ctx.lineTo(150,90);) at the angle I thought it would which is from the end of the first lineTo at 25,25 to a 150,90 at a 45 degree angle. If I use -Math.PI*7/4 I get what looks like a 45 degree angle, but it points the wrong way. Math.PI*5/4 goes the wrong way or rotation.

My question asks about the Unit Circle. I don't really need them all at once, just the ability to know how to draw them if I need them.

Upvotes: 0

Views: 917

Answers (2)

skaa
skaa

Reputation: 79

The canvas is rotating this way:

enter image description here

Upvotes: 1

AgataB
AgataB

Reputation: 647

Consider the following example, without the y offset: Simplified problem

Given by the code:

var canvas = document.getElementById("my-canvas");  
var ctx = canvas.getContext("2d");  

ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(250, 0);
ctx.rotate(45*Math.PI/180);  //45 degrees
ctx.lineTo(150,0);
ctx.stroke();
ctx.beginPath();

ctx.moveTo(0,0);
ctx.strokeStyle = '#ff0000';
ctx.lineTo(350,0); 
ctx.font = "30px Arial";
ctx.fillText("New x axis",100,50);
ctx.stroke();

The red line is the new x axis, and the black line touches it exactly at a distance of 150 from the origin.

Now overlaying the same red line with your coordinates (and rotating by 45 degrees, so that it doesn't go off screen), we get

Using original coords

The black line ends at a point which is indeed (150,90), however at the new coordinate system. JSFiddle here

If you want the angle between the two line segments to be exactly what you pass in rotate(...), then keep drawing "horizontal" lines, but translate the origin to the end of each line segment, so you rotate about this point, not the top-left corner, using ctx.translate(<current point>). For example: https://jsfiddle.net/Douma37/65z1p38z/ (this goes off canvas, but has minimal interferance with your code).

Hope that helps!

Upvotes: 0

Related Questions