roundRect.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export function buildPath(ctx, shape) {
  2. var x = shape.x;
  3. var y = shape.y;
  4. var width = shape.width;
  5. var height = shape.height;
  6. var r = shape.r;
  7. var r1;
  8. var r2;
  9. var r3;
  10. var r4;
  11. if (width < 0) {
  12. x = x + width;
  13. width = -width;
  14. }
  15. if (height < 0) {
  16. y = y + height;
  17. height = -height;
  18. }
  19. if (typeof r === 'number') {
  20. r1 = r2 = r3 = r4 = r;
  21. }
  22. else if (r instanceof Array) {
  23. if (r.length === 1) {
  24. r1 = r2 = r3 = r4 = r[0];
  25. }
  26. else if (r.length === 2) {
  27. r1 = r3 = r[0];
  28. r2 = r4 = r[1];
  29. }
  30. else if (r.length === 3) {
  31. r1 = r[0];
  32. r2 = r4 = r[1];
  33. r3 = r[2];
  34. }
  35. else {
  36. r1 = r[0];
  37. r2 = r[1];
  38. r3 = r[2];
  39. r4 = r[3];
  40. }
  41. }
  42. else {
  43. r1 = r2 = r3 = r4 = 0;
  44. }
  45. var total;
  46. if (r1 + r2 > width) {
  47. total = r1 + r2;
  48. r1 *= width / total;
  49. r2 *= width / total;
  50. }
  51. if (r3 + r4 > width) {
  52. total = r3 + r4;
  53. r3 *= width / total;
  54. r4 *= width / total;
  55. }
  56. if (r2 + r3 > height) {
  57. total = r2 + r3;
  58. r2 *= height / total;
  59. r3 *= height / total;
  60. }
  61. if (r1 + r4 > height) {
  62. total = r1 + r4;
  63. r1 *= height / total;
  64. r4 *= height / total;
  65. }
  66. ctx.moveTo(x + r1, y);
  67. ctx.lineTo(x + width - r2, y);
  68. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  69. ctx.lineTo(x + width, y + height - r3);
  70. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  71. ctx.lineTo(x + r4, y + height);
  72. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  73. ctx.lineTo(x, y + r1);
  74. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  75. }