Image.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. * @type {Box2}
  17. */
  18. this.box = new Box2();
  19. /**
  20. * Image source DOM element.
  21. *
  22. * @type {HTMLImageElement}
  23. */
  24. this.image = document.createElement("img");
  25. if(src !== undefined)
  26. {
  27. this.setImage(src);
  28. }
  29. }
  30. Image.prototype = Object.create(Object2D.prototype);
  31. Image.prototype.constructor = Image;
  32. Image.prototype.type = "Image";
  33. Object2D.register(Image, "Image");
  34. /**
  35. * Set the image of the object.
  36. *
  37. * Automatically sets the box size to match the image.
  38. *
  39. * @param {string} src Source URL of the image.
  40. */
  41. Image.prototype.setImage = function(src)
  42. {
  43. var self = this;
  44. this.image.onload = function()
  45. {
  46. self.box.min.set(0, 0);
  47. self.box.max.set(this.naturalWidth, this.naturalHeight);
  48. };
  49. this.image.src = src;
  50. };
  51. Image.prototype.isInside = function(point)
  52. {
  53. return this.box.containsPoint(point);
  54. };
  55. Image.prototype.draw = function(context, viewport, canvas)
  56. {
  57. if(this.image.src.length > 0)
  58. {
  59. 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);
  60. }
  61. };
  62. Image.prototype.serialize = function(recursive)
  63. {
  64. var data = Object2D.prototype.serialize.call(this, recursive);
  65. data.box = this.box.toArray();
  66. data.image = this.image.src;
  67. return data;
  68. };
  69. Image.prototype.parse = function(data, root)
  70. {
  71. Object2D.prototype.parse.call(this, data, root);
  72. this.box.fromArray(data.box);
  73. this.image.src = data.image;
  74. };
  75. export {Image};