CVImageElement.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import {
  2. extendPrototype,
  3. } from '../../utils/functionExtensions';
  4. import createTag from '../../utils/helpers/html_elements';
  5. import RenderableElement from '../helpers/RenderableElement';
  6. import BaseElement from '../BaseElement';
  7. import TransformElement from '../helpers/TransformElement';
  8. import HierarchyElement from '../helpers/HierarchyElement';
  9. import FrameElement from '../helpers/FrameElement';
  10. import CVBaseElement from './CVBaseElement';
  11. import IImageElement from '../ImageElement';
  12. import SVGShapeElement from '../svgElements/SVGShapeElement';
  13. function CVImageElement(data, globalData, comp) {
  14. this.assetData = globalData.getAssetData(data.refId);
  15. this.img = globalData.imageLoader.getAsset(this.assetData);
  16. this.initElement(data, globalData, comp);
  17. }
  18. extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVImageElement);
  19. CVImageElement.prototype.initElement = SVGShapeElement.prototype.initElement;
  20. CVImageElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame;
  21. CVImageElement.prototype.createContent = function () {
  22. if (this.img.width && (this.assetData.w !== this.img.width || this.assetData.h !== this.img.height)) {
  23. var canvas = createTag('canvas');
  24. canvas.width = this.assetData.w;
  25. canvas.height = this.assetData.h;
  26. var ctx = canvas.getContext('2d');
  27. var imgW = this.img.width;
  28. var imgH = this.img.height;
  29. var imgRel = imgW / imgH;
  30. var canvasRel = this.assetData.w / this.assetData.h;
  31. var widthCrop;
  32. var heightCrop;
  33. var par = this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio;
  34. if ((imgRel > canvasRel && par === 'xMidYMid slice') || (imgRel < canvasRel && par !== 'xMidYMid slice')) {
  35. heightCrop = imgH;
  36. widthCrop = heightCrop * canvasRel;
  37. } else {
  38. widthCrop = imgW;
  39. heightCrop = widthCrop / canvasRel;
  40. }
  41. ctx.drawImage(this.img, (imgW - widthCrop) / 2, (imgH - heightCrop) / 2, widthCrop, heightCrop, 0, 0, this.assetData.w, this.assetData.h);
  42. this.img = canvas;
  43. }
  44. };
  45. CVImageElement.prototype.renderInnerContent = function () {
  46. this.canvasContext.drawImage(this.img, 0, 0);
  47. };
  48. CVImageElement.prototype.destroy = function () {
  49. this.img = null;
  50. };
  51. export default CVImageElement;