Search code examples
javascriptmathcanvasangle

How to find smaller angle from startAngle and endAngle in html canvas arc?


I want to always have a smaller angle and I don't know how to decide counterclockwise ore not in drawing arc in html canvas.

This is my code

this.ctx.beginPath();

const startAngle = Math.atan2(P1.y - P2.y, P1.x - P2.x);
const endAngle = Math.atan2(P3.y - P2.y, P3.x - P2.x);

this.ctx.arc(P2.x, P2.y, 40, startAngle, endAngle, true);

smaller angle larger angle


Solution

  • You're dealing with vectors in the 2D plane. Counterclockwise is determined by the right hand rule and the out-of-plane direction.

    The vector cross-product is the operation you need. The angle is counter clockwise if the sign of the vector you obtain by crossing the first vector into the second is positive.

    The cross product will give you a normalized vector that is either (0, 0, 1) for counterclockwise or (0, 0, -1) for clockwise. Normalize the cross product and look at the sign of the z-component.