RoundedBox.js 2.4 KB

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