在Canvas中使用arc()绘制圆弧时,需要传入起始角度。很多情况下已知圆心以及圆弧起始点的坐标,这时候只要计算出起始点与圆心的角度即可。注意,本文中的角度的为Canvas中的角度定义(顺时针)。

  1. /**
  2. * Calculate the clockwise angle between point p and center
  3. * @param {Object} p, the point in format of {x, y}
  4. * @param {Object} center, the center, in format of {x, y}
  5. * @return {Number} the angle, in radian measure but not degeree, valued in [0, 2PI)
  6. */
  7. var angle = function(p, center) {
  8. var y = p.y - center.y;
  9. var x = p.x - center.x;
  10. var a = Math.atan(y / x);
  11. if (a > 0) {
  12. // the angle is in first quadrant or third quadrant
  13. return y > 0 ? a : a + Math.PI;
  14. } else {
  15. // the angle is in second quadrant or fourth quadrant
  16. return y > 0 ? a + Math.PI : a + Math.PI * 2;
  17. }
  18. };