Image.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. * @class
  9. * @param {string} [src] Source URL of the image.
  10. */
  11. function Image(src)
  12. {
  13. Object2D.call(this);
  14. /**
  15. * Box object containing the size of the object.
  16. */
  17. this.box = new Box2();
  18. /**
  19. * Image source DOM element.
  20. */
  21. this.image = document.createElement("img");
  22. if(src !== undefined)
  23. {
  24. this.setImage(src);
  25. }
  26. }
  27. Image.prototype = Object.create(Object2D.prototype);
  28. /**
  29. * Set the image of the object.
  30. *
  31. * Automatically sets the box size to match the image.
  32. *
  33. * @param {string} src Source URL of the image.
  34. */
  35. Image.prototype.setImage = function(src)
  36. {
  37. var self = this;
  38. this.image.onload = function()
  39. {
  40. self.box.min.set(0, 0);
  41. self.box.max.set(this.naturalWidth, this.naturalHeight);
  42. };
  43. this.image.src = src;
  44. };
  45. Image.prototype.isInside = function(point)
  46. {
  47. return this.box.containsPoint(point);
  48. };
  49. Image.prototype.draw = function(context)
  50. {
  51. 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);
  52. };
  53. export {Image};