RoundedBox.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import {Box} from "./Box";
  2. /**
  3. * Rounded box object draw a rectangular object with rounded corners.
  4. *
  5. * @class
  6. * @extends {Box}
  7. */
  8. function RoundedBox()
  9. {
  10. Box.call(this);
  11. /**
  12. * Radius of the circular section that makes up the box corners.
  13. *
  14. * @type {number}
  15. */
  16. this.radius = 5;
  17. }
  18. RoundedBox.prototype = Object.create(Box.prototype);
  19. /**
  20. * Draw a rounded rectangle into the canvas context using path to draw the rounded rectangle.
  21. *
  22. * @param {CanvasRenderingContext2D} context
  23. * @param {number} x The top left x coordinate
  24. * @param {number} y The top left y coordinate
  25. * @param {number} width The width of the rectangle
  26. * @param {number} height The height of the rectangle
  27. * @param {number} radius Radius of the rectangle corners.
  28. */
  29. RoundedBox.roundRect = function(context, x, y, width, height, radius)
  30. {
  31. context.beginPath();
  32. context.moveTo(x + radius, y);
  33. context.lineTo(x + width - radius, y);
  34. context.quadraticCurveTo(x + width, y, x + width, y + radius);
  35. context.lineTo(x + width, y + height - radius);
  36. context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  37. context.lineTo(x + radius, y + height);
  38. context.quadraticCurveTo(x, y + height, x, y + height - radius);
  39. context.lineTo(x, y + radius);
  40. context.quadraticCurveTo(x, y, x + radius, y);
  41. context.closePath();
  42. };
  43. RoundedBox.prototype.draw = function(context, viewport, canvas)
  44. {
  45. var width = this.box.max.x - this.box.min.x;
  46. var height = this.box.max.y - this.box.min.y;
  47. if(this.fillStyle !== null)
  48. {
  49. context.fillStyle = this.fillStyle;
  50. RoundedBox.roundRect(context, this.box.min.x, this.box.min.y, width, height, this.radius);
  51. context.fill();
  52. }
  53. if(this.strokeStyle !== null)
  54. {
  55. context.lineWidth = this.lineWidth;
  56. context.strokeStyle = this.strokeStyle;
  57. RoundedBox.roundRect(context, this.box.min.x, this.box.min.y, width, height, this.radius);
  58. context.stroke();
  59. }
  60. };
  61. export {RoundedBox};