Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a Triangle around its center with JavaScript

It's late on a Friday and I'm scratching my head on this one.

I'm trying to draw an equilateral triangle and rotate it around it's center but for some reason I'm having trouble determining it's center point.

Here's a JSFiddle where you can see how I'm translating to the center of the canvas and then drawing the Triangle out from there using the equation:

var width = 30;
var height = width * (Math.sqrt(3)/2);

To determine the ratio of width / height.

What am I missing here? Any thoughts would be most appreciated.

like image 685
braitsch Avatar asked Mar 24 '12 02:03

braitsch


1 Answers

You're rotating around (0, 0), which in this case isn't the center of your triangle.

A triangle with vertices (0, -h / 2), (w / 2, h / 2), (-w / 2, h / 2) has a center that's the average of those three positions. Fairly obviously, (1/3)(-h / 2) + (2/3)(h / 2) = h / 6. So that's the actual y-coordinate of the center of your triangle.

One solution might be to move your triangle to (0, (-2/3)*h), (w / 2, h / 3), (-w / 2, h / 3).

like image 181
John Calsbeek Avatar answered Sep 23 '22 07:09

John Calsbeek