Image.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. import {Object2D} from "../Object2D.js";
  3. import {Box2} from "../math/Box2.js";
  4. import {Vector2} from "../math/Vector2.js";
  5. /**
  6. * Image object is used to draw an image from URL.
  7. */
  8. function Image(src)
  9. {
  10. Object2D.call(this);
  11. /**
  12. * Box object containing the size of the object.
  13. */
  14. this.box = new Box2(new Vector2(0, 0), new Vector2(0, 0));
  15. /**
  16. * Image source DOM element.
  17. */
  18. this.image = document.createElement("img");
  19. this.setImage(src);
  20. }
  21. Image.prototype = Object.create(Object2D.prototype);
  22. /**
  23. * Set the image of the object.
  24. *
  25. * Automatically sets the box size to match the image.
  26. */
  27. Image.prototype.setImage = function(src)
  28. {
  29. var self = this;
  30. this.image.onload = function()
  31. {
  32. self.box.min.set(0, 0);
  33. self.box.max.set(this.naturalWidth, this.naturalHeight);
  34. };
  35. this.image.src = src;
  36. };
  37. Image.prototype.isInside = function(point)
  38. {
  39. return this.box.containsPoint(point);
  40. };
  41. Image.prototype.draw = function(context)
  42. {
  43. context.drawImage(this.image, 0, 0, this.image.naturalWidth, this.image.naturalHeight, this.box.min.x, this.box.min.y, this.box.max.x - this.box.min.x, this.box.max.y - this.box.min.y);
  44. };
  45. export {Image};