Pattern.js 1.6 KB

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