Pattern.js 1.6 KB

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