Pattern.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. */
  14. function Pattern(src)
  15. {
  16. Object2D.call(this);
  17. /**
  18. * Box object containing the size of the object.
  19. */
  20. this.box = new Box2();
  21. /**
  22. * Image source DOM element.
  23. */
  24. this.image = document.createElement("img");
  25. /**
  26. * A DOMString indicating how to repeat the pattern image.
  27. */
  28. this.repetition = "repeat"
  29. if(src !== undefined)
  30. {
  31. this.setImage(src);
  32. }
  33. }
  34. Pattern.prototype = Object.create(Object2D.prototype);
  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. //pattern.setTransform();
  62. context.fillStyle = pattern;
  63. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  64. }
  65. };
  66. export {Pattern};