6e41012a8d7862ab36f86c4d238f1fd3e97fe6d54478b9058134fa4f90e37402fae0cba97975c6836bac85722ec1c1430699bac6644aed8a4c90df12f01215 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * n角星(n>3)
  3. * @module zrender/graphic/shape/Star
  4. */
  5. import Path, { PathProps } from '../Path';
  6. const PI = Math.PI;
  7. const cos = Math.cos;
  8. const sin = Math.sin;
  9. export class StarShape {
  10. cx = 0
  11. cy = 0
  12. n = 3
  13. r0: number
  14. r = 0
  15. }
  16. export interface StarProps extends PathProps {
  17. shape?: Partial<StarShape>
  18. }
  19. class Star extends Path<StarProps> {
  20. shape: StarShape
  21. constructor(opts?: StarProps) {
  22. super(opts);
  23. }
  24. getDefaultShape() {
  25. return new StarShape();
  26. }
  27. buildPath(ctx: CanvasRenderingContext2D, shape: StarShape) {
  28. const n = shape.n;
  29. if (!n || n < 2) {
  30. return;
  31. }
  32. const x = shape.cx;
  33. const y = shape.cy;
  34. const r = shape.r;
  35. let r0 = shape.r0;
  36. // 如果未指定内部顶点外接圆半径,则自动计算
  37. if (r0 == null) {
  38. r0 = n > 4
  39. // 相隔的外部顶点的连线的交点,
  40. // 被取为内部交点,以此计算r0
  41. ? r * cos(2 * PI / n) / cos(PI / n)
  42. // 二三四角星的特殊处理
  43. : r / 3;
  44. }
  45. const dStep = PI / n;
  46. let deg = -PI / 2;
  47. const xStart = x + r * cos(deg);
  48. const yStart = y + r * sin(deg);
  49. deg += dStep;
  50. // 记录边界点,用于判断inside
  51. ctx.moveTo(xStart, yStart);
  52. for (let i = 0, end = n * 2 - 1, ri; i < end; i++) {
  53. ri = i % 2 === 0 ? r0 : r;
  54. ctx.lineTo(x + ri * cos(deg), y + ri * sin(deg));
  55. deg += dStep;
  56. }
  57. ctx.closePath();
  58. }
  59. }
  60. Star.prototype.type = 'star';
  61. export default Star;