Image.js 1.3 KB

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