Ian Marshall logo

Ian Marshall

Q: I'm trying to draw an equilateral triangle on a canvas, and then rotate it around its center by 90 degrees once you click the triangle, but for some reason I'm having trouble determining its center point. How would you go about doing this in Javascript?

Rotate a triangle around its center with JavaScript?

You can find the centroid of any polygon by averaging all of its vertices. If, for example, you know the exact x,y coordinates of the points of your triangle, then add up all the x values and divide by three, then add up all the y values and divide by three. That's your center.

Then, of course, you could ctx.translate(centroidX, centroidY) to that point and ctx.rotate("90deg") before drawing your triangle.

Ian