简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM