roundRect.js 1.9 KB

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