Image.js 1.3 KB

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