Pattern.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. this.box = new Box2();
  19. /**
  20. * Image source DOM element.
  21. */
  22. this.image = document.createElement("img");
  23. /**
  24. * A DOMString indicating how to repeat the pattern image.
  25. */
  26. this.repetition = "repeat"
  27. if(src !== undefined)
  28. {
  29. this.setImage(src);
  30. }
  31. }
  32. Pattern.prototype = Object.create(Object2D.prototype);
  33. /**
  34. * Set the image of the object.
  35. *
  36. * Automatically sets the box size to match the image.
  37. */
  38. Pattern.prototype.setImage = function(src)
  39. {
  40. var self = this;
  41. this.image.onload = function()
  42. {
  43. self.box.min.set(0, 0);
  44. self.box.max.set(this.naturalWidth, this.naturalHeight);
  45. };
  46. this.image.src = src;
  47. };
  48. Pattern.prototype.isInside = function(point)
  49. {
  50. return this.box.containsPoint(point);
  51. };
  52. Pattern.prototype.draw = function(context, viewport, canvas)
  53. {
  54. var width = this.box.max.x - this.box.min.x;
  55. var height = this.box.max.y - this.box.min.y;
  56. if(this.image.src.length > 0)
  57. {
  58. var pattern = context.createPattern(this.image, this.repetition);
  59. context.fillStyle = pattern;
  60. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  61. }
  62. };
  63. export {Pattern};