Pattern.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import {Object2D} from "../Object2D.js";
  2. import {Box2} from "../math/Box2.js";
  3. /**
  4. * Pattern object draw a image repeated as a pattern.
  5. *
  6. * Its similar to the Image class but the image can be repeat infinitely.
  7. *
  8. * @class
  9. * @extends {Object2D}
  10. * @param {string} src Source image URL.
  11. */
  12. function Pattern(src)
  13. {
  14. Object2D.call(this);
  15. /**
  16. * Box object containing the size of the object.
  17. *
  18. * @type {Box2}
  19. */
  20. this.box = new Box2();
  21. /**
  22. * Image source DOM element.
  23. *
  24. * @type {Element}
  25. */
  26. this.image = document.createElement("img");
  27. /**
  28. * Repetition indicates how the pattern image should be repeated.
  29. *
  30. * @type {string}
  31. */
  32. this.repetition = "repeat"
  33. if(src !== undefined)
  34. {
  35. this.setImage(src);
  36. }
  37. }
  38. Pattern.prototype = Object.create(Object2D.prototype);
  39. Pattern.prototype.constructor = Pattern;
  40. Pattern.prototype.type = "Pattern";
  41. /**
  42. * Set the image source of the object. Can be anything accepted by the src field of an img element.
  43. *
  44. * Automatically sets the box size to match the image.
  45. *
  46. * @param {string} src Image source string.
  47. */
  48. Pattern.prototype.setImage = function(src)
  49. {
  50. var self = this;
  51. this.image.onload = function()
  52. {
  53. self.box.min.set(0, 0);
  54. self.box.max.set(this.naturalWidth, this.naturalHeight);
  55. };
  56. this.image.src = src;
  57. };
  58. Pattern.prototype.isInside = function(point)
  59. {
  60. return this.box.containsPoint(point);
  61. };
  62. Pattern.prototype.draw = function(context, viewport, canvas)
  63. {
  64. var width = this.box.max.x - this.box.min.x;
  65. var height = this.box.max.y - this.box.min.y;
  66. if(this.image.src.length > 0)
  67. {
  68. var pattern = context.createPattern(this.image, this.repetition);
  69. context.fillStyle = pattern;
  70. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  71. }
  72. };
  73. export {Pattern};