RoundedBox.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. RoundedBox.prototype.constructor = RoundedBox;
  20. RoundedBox.prototype.type = "RoundedBox";
  21. /**
  22. * Draw a rounded rectangle into the canvas context using path to draw the rounded rectangle.
  23. *
  24. * @param {CanvasRenderingContext2D} context
  25. * @param {number} x The top left x coordinate
  26. * @param {number} y The top left y coordinate
  27. * @param {number} width The width of the rectangle
  28. * @param {number} height The height of the rectangle
  29. * @param {number} radius Radius of the rectangle corners.
  30. */
  31. RoundedBox.roundRect = function(context, x, y, width, height, radius)
  32. {
  33. context.beginPath();
  34. context.moveTo(x + radius, y);
  35. context.lineTo(x + width - radius, y);
  36. context.quadraticCurveTo(x + width, y, x + width, y + radius);
  37. context.lineTo(x + width, y + height - radius);
  38. context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  39. context.lineTo(x + radius, y + height);
  40. context.quadraticCurveTo(x, y + height, x, y + height - radius);
  41. context.lineTo(x, y + radius);
  42. context.quadraticCurveTo(x, y, x + radius, y);
  43. context.closePath();
  44. };
  45. RoundedBox.prototype.draw = function(context, viewport, canvas)
  46. {
  47. var width = this.box.max.x - this.box.min.x;
  48. var height = this.box.max.y - this.box.min.y;
  49. if(this.fillStyle !== null)
  50. {
  51. context.fillStyle = this.fillStyle;
  52. RoundedBox.roundRect(context, this.box.min.x, this.box.min.y, width, height, this.radius);
  53. context.fill();
  54. }
  55. if(this.strokeStyle !== null)
  56. {
  57. context.lineWidth = this.lineWidth;
  58. context.strokeStyle = this.strokeStyle;
  59. RoundedBox.roundRect(context, this.box.min.x, this.box.min.y, width, height, this.radius);
  60. context.stroke();
  61. }
  62. };
  63. RoundedBox.prototype.serialize = function(recursive)
  64. {
  65. var data = Box.prototype.serialize.call(this, recursive);
  66. data.radius = this.radius;
  67. return data;
  68. };
  69. RoundedBox.prototype.parse = function(data)
  70. {
  71. Box.prototype.parse.call(this, data);
  72. this.radius = data.radius;
  73. };
  74. export {RoundedBox};