moroccan_dev
moroccan_dev

Reputation: 310

measuring angles on HTML 5 canvas element?

I am confused when implementing (measure) angles in an HTML5 canvas especially after rotating objects

Let's assume I have drawn a shape like this

ctx.moveTo(100,100)//center of canvas
ctx.lineTo(0,200)//left bottom
ctx.lineTo(200,200)//right bottom

We know it is a 45 degrees or pi*2/4 angle.

But how do I figure it out using Math functions to see if the shape was rotated or not? And how to re-measure it after changing the x and y of the shape(first point) ?

Upvotes: 0

Views: 900

Answers (1)

Brennan
Brennan

Reputation: 5732

First things first, you will need to make sure the points are stored in some sort of data structure, as it won't be easy to pull the points from the canvas itself. Something like an array of arrays:

var angle = [[100,100], [0,200], [200,200]];

Now, you need to convert your lines to vectors:

var AB = [angle[1][0]-angle[0][0], angle[1][1]-angle[0][1]];
var BC = [angle[2][0]-angle[1][0], angle[2][1]-angle[1][1]];

Now find the dot-product of the two:

var dot_product = (AB[0]*BC[0]) + (AB[1]*BC[1]);//not dot-product

Now you need to find the length (magnitude) of the vectors:

var ABmagnitude = Math.sqrt(Math.pow(AB[0],2) + Math.pow(AB[1],2));
var BCmagnitude = Math.sqrt(Math.pow(BC[0],2) + Math.pow(BC[1],2));

Now you put it all together by dividing the dot product by the product of the two magnitudes and getting the arcosine:

var theta = Math.acos(dot_product/(ABmagnitude*BCmagnitude));

You mentioned rotation, but unless you are only rotating one line, the angle will stay the same.

Upvotes: 3

Related Questions