image.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. import { Nullable } from "babylonjs/types";
  2. import { Observable } from "babylonjs/Misc/observable";
  3. import { Tools } from "babylonjs/Misc/tools";
  4. import { Control } from "./control";
  5. import { Measure } from "../measure";
  6. import { _TypeStore } from "babylonjs/Misc/typeStore";
  7. import { serialize } from "babylonjs/Misc/decorators";
  8. /**
  9. * Class used to create 2D images
  10. */
  11. export class Image extends Control {
  12. private _workingCanvas: Nullable<HTMLCanvasElement> = null;
  13. private _domImage: HTMLImageElement;
  14. private _imageWidth: number;
  15. private _imageHeight: number;
  16. private _loaded = false;
  17. private _stretch = Image.STRETCH_FILL;
  18. private _source: Nullable<string>;
  19. private _autoScale = false;
  20. private _sourceLeft = 0;
  21. private _sourceTop = 0;
  22. private _sourceWidth = 0;
  23. private _sourceHeight = 0;
  24. private _svgAttributesComputationCompleted: boolean = false;
  25. private _isSVG: boolean = false;
  26. private _cellWidth: number = 0;
  27. private _cellHeight: number = 0;
  28. private _cellId: number = -1;
  29. private _sliceLeft: number;
  30. private _sliceRight: number;
  31. private _sliceTop: number;
  32. private _sliceBottom: number;
  33. private _populateNinePatchSlicesFromImage = false;
  34. private _detectPointerOnOpaqueOnly: boolean;
  35. private _imageDataCache: {
  36. data: Uint8ClampedArray | null;
  37. key: string;
  38. } = { data: null, key: "" };
  39. /**
  40. * Observable notified when the content is loaded
  41. */
  42. public onImageLoadedObservable = new Observable<Image>();
  43. /**
  44. * Observable notified when _sourceLeft, _sourceTop, _sourceWidth and _sourceHeight are computed
  45. */
  46. public onSVGAttributesComputedObservable = new Observable<Image>();
  47. /**
  48. * Gets a boolean indicating that the content is loaded
  49. */
  50. public get isLoaded(): boolean {
  51. return this._loaded;
  52. }
  53. /**
  54. * Gets or sets a boolean indicating if pointers should only be validated on pixels with alpha > 0.
  55. * Beware using this as this will comsume more memory as the image has to be stored twice
  56. */
  57. @serialize()
  58. public get detectPointerOnOpaqueOnly(): boolean {
  59. return this._detectPointerOnOpaqueOnly;
  60. }
  61. public set detectPointerOnOpaqueOnly(value: boolean) {
  62. if (this._detectPointerOnOpaqueOnly === value) {
  63. return;
  64. }
  65. this._detectPointerOnOpaqueOnly = value;
  66. }
  67. /**
  68. * Gets or sets the left value for slicing (9-patch)
  69. */
  70. @serialize()
  71. public get sliceLeft(): number {
  72. return this._sliceLeft;
  73. }
  74. public set sliceLeft(value: number) {
  75. if (this._sliceLeft === value) {
  76. return;
  77. }
  78. this._sliceLeft = value;
  79. this._markAsDirty();
  80. }
  81. /**
  82. * Gets or sets the right value for slicing (9-patch)
  83. */
  84. @serialize()
  85. public get sliceRight(): number {
  86. return this._sliceRight;
  87. }
  88. public set sliceRight(value: number) {
  89. if (this._sliceRight === value) {
  90. return;
  91. }
  92. this._sliceRight = value;
  93. this._markAsDirty();
  94. }
  95. /**
  96. * Gets or sets the top value for slicing (9-patch)
  97. */
  98. @serialize()
  99. public get sliceTop(): number {
  100. return this._sliceTop;
  101. }
  102. public set sliceTop(value: number) {
  103. if (this._sliceTop === value) {
  104. return;
  105. }
  106. this._sliceTop = value;
  107. this._markAsDirty();
  108. }
  109. /**
  110. * Gets or sets the bottom value for slicing (9-patch)
  111. */
  112. @serialize()
  113. public get sliceBottom(): number {
  114. return this._sliceBottom;
  115. }
  116. public set sliceBottom(value: number) {
  117. if (this._sliceBottom === value) {
  118. return;
  119. }
  120. this._sliceBottom = value;
  121. this._markAsDirty();
  122. }
  123. /**
  124. * Gets or sets the left coordinate in the source image
  125. */
  126. @serialize()
  127. public get sourceLeft(): number {
  128. return this._sourceLeft;
  129. }
  130. public set sourceLeft(value: number) {
  131. if (this._sourceLeft === value) {
  132. return;
  133. }
  134. this._sourceLeft = value;
  135. this._markAsDirty();
  136. }
  137. /**
  138. * Gets or sets the top coordinate in the source image
  139. */
  140. @serialize()
  141. public get sourceTop(): number {
  142. return this._sourceTop;
  143. }
  144. public set sourceTop(value: number) {
  145. if (this._sourceTop === value) {
  146. return;
  147. }
  148. this._sourceTop = value;
  149. this._markAsDirty();
  150. }
  151. /**
  152. * Gets or sets the width to capture in the source image
  153. */
  154. @serialize()
  155. public get sourceWidth(): number {
  156. return this._sourceWidth;
  157. }
  158. public set sourceWidth(value: number) {
  159. if (this._sourceWidth === value) {
  160. return;
  161. }
  162. this._sourceWidth = value;
  163. this._markAsDirty();
  164. }
  165. /**
  166. * Gets or sets the height to capture in the source image
  167. */
  168. @serialize()
  169. public get sourceHeight(): number {
  170. return this._sourceHeight;
  171. }
  172. public set sourceHeight(value: number) {
  173. if (this._sourceHeight === value) {
  174. return;
  175. }
  176. this._sourceHeight = value;
  177. this._markAsDirty();
  178. }
  179. /**
  180. * Gets the image width
  181. */
  182. @serialize()
  183. public get imageWidth(): number {
  184. return this._imageWidth;
  185. }
  186. /**
  187. * Gets the image height
  188. */
  189. @serialize()
  190. public get imageHeight(): number {
  191. return this._imageHeight;
  192. }
  193. /**
  194. * Gets or sets a boolean indicating if nine patch slices (left, top, right, bottom) should be read from image data
  195. */
  196. @serialize()
  197. public get populateNinePatchSlicesFromImage(): boolean {
  198. return this._populateNinePatchSlicesFromImage;
  199. }
  200. public set populateNinePatchSlicesFromImage(value: boolean) {
  201. if (this._populateNinePatchSlicesFromImage === value) {
  202. return;
  203. }
  204. this._populateNinePatchSlicesFromImage = value;
  205. if (this._populateNinePatchSlicesFromImage && this._loaded) {
  206. this._extractNinePatchSliceDataFromImage();
  207. }
  208. }
  209. /** Indicates if the format of the image is SVG */
  210. public get isSVG(): boolean {
  211. return this._isSVG;
  212. }
  213. /** Gets the status of the SVG attributes computation (sourceLeft, sourceTop, sourceWidth, sourceHeight) */
  214. public get svgAttributesComputationCompleted(): boolean {
  215. return this._svgAttributesComputationCompleted;
  216. }
  217. /**
  218. * Gets or sets a boolean indicating if the image can force its container to adapt its size
  219. * @see https://doc.babylonjs.com/how_to/gui#image
  220. */
  221. @serialize()
  222. public get autoScale(): boolean {
  223. return this._autoScale;
  224. }
  225. public set autoScale(value: boolean) {
  226. if (this._autoScale === value) {
  227. return;
  228. }
  229. this._autoScale = value;
  230. if (value && this._loaded) {
  231. this.synchronizeSizeWithContent();
  232. }
  233. }
  234. /** Gets or sets the streching mode used by the image */
  235. @serialize()
  236. public get stretch(): number {
  237. return this._stretch;
  238. }
  239. public set stretch(value: number) {
  240. if (this._stretch === value) {
  241. return;
  242. }
  243. this._stretch = value;
  244. this._markAsDirty();
  245. }
  246. /** @hidden */
  247. public _rotate90(n: number, preserveProperties: boolean = false): Image {
  248. let canvas = document.createElement("canvas");
  249. const context = canvas.getContext("2d")!;
  250. const width = this._domImage.width;
  251. const height = this._domImage.height;
  252. canvas.width = height;
  253. canvas.height = width;
  254. context.translate(canvas.width / 2, canvas.height / 2);
  255. context.rotate((n * Math.PI) / 2);
  256. context.drawImage(this._domImage, 0, 0, width, height, -width / 2, -height / 2, width, height);
  257. const dataUrl: string = canvas.toDataURL("image/jpg");
  258. const rotatedImage = new Image(this.name + "rotated", dataUrl);
  259. if (preserveProperties) {
  260. rotatedImage._stretch = this._stretch;
  261. rotatedImage._autoScale = this._autoScale;
  262. rotatedImage._cellId = this._cellId;
  263. rotatedImage._cellWidth = n % 1 ? this._cellHeight : this._cellWidth;
  264. rotatedImage._cellHeight = n % 1 ? this._cellWidth : this._cellHeight;
  265. }
  266. this._handleRotationForSVGImage(this, rotatedImage, n);
  267. this._imageDataCache.data = null;
  268. return rotatedImage;
  269. }
  270. private _handleRotationForSVGImage(srcImage: Image, dstImage: Image, n: number): void {
  271. if (!srcImage._isSVG) {
  272. return;
  273. }
  274. if (srcImage._svgAttributesComputationCompleted) {
  275. this._rotate90SourceProperties(srcImage, dstImage, n);
  276. this._markAsDirty();
  277. } else {
  278. srcImage.onSVGAttributesComputedObservable.addOnce(() => {
  279. this._rotate90SourceProperties(srcImage, dstImage, n);
  280. this._markAsDirty();
  281. });
  282. }
  283. }
  284. private _rotate90SourceProperties(srcImage: Image, dstImage: Image, n: number): void {
  285. let srcLeft = srcImage.sourceLeft,
  286. srcTop = srcImage.sourceTop,
  287. srcWidth = srcImage.domImage.width,
  288. srcHeight = srcImage.domImage.height;
  289. let dstLeft = srcLeft,
  290. dstTop = srcTop,
  291. dstWidth = srcImage.sourceWidth,
  292. dstHeight = srcImage.sourceHeight;
  293. if (n != 0) {
  294. let mult = n < 0 ? -1 : 1;
  295. n = n % 4;
  296. for (let i = 0; i < Math.abs(n); ++i) {
  297. dstLeft = -(srcTop - srcHeight / 2) * mult + srcHeight / 2;
  298. dstTop = (srcLeft - srcWidth / 2) * mult + srcWidth / 2;
  299. [dstWidth, dstHeight] = [dstHeight, dstWidth];
  300. if (n < 0) {
  301. dstTop -= dstHeight;
  302. } else {
  303. dstLeft -= dstWidth;
  304. }
  305. srcLeft = dstLeft;
  306. srcTop = dstTop;
  307. [srcWidth, srcHeight] = [srcHeight, srcWidth];
  308. }
  309. }
  310. dstImage.sourceLeft = dstLeft;
  311. dstImage.sourceTop = dstTop;
  312. dstImage.sourceWidth = dstWidth;
  313. dstImage.sourceHeight = dstHeight;
  314. }
  315. private _extractNinePatchSliceDataFromImage() {
  316. if (!this._workingCanvas) {
  317. this._workingCanvas = document.createElement("canvas");
  318. }
  319. const canvas = this._workingCanvas;
  320. const context = canvas.getContext("2d")!;
  321. const width = this._domImage.width;
  322. const height = this._domImage.height;
  323. canvas.width = width;
  324. canvas.height = height;
  325. context.drawImage(this._domImage, 0, 0, width, height);
  326. const imageData = context.getImageData(0, 0, width, height);
  327. // Left and right
  328. this._sliceLeft = -1;
  329. this._sliceRight = -1;
  330. for (var x = 0; x < width; x++) {
  331. const alpha = imageData.data[x * 4 + 3];
  332. if (alpha > 127 && this._sliceLeft === -1) {
  333. this._sliceLeft = x;
  334. continue;
  335. }
  336. if (alpha < 127 && this._sliceLeft > -1) {
  337. this._sliceRight = x;
  338. break;
  339. }
  340. }
  341. // top and bottom
  342. this._sliceTop = -1;
  343. this._sliceBottom = -1;
  344. for (var y = 0; y < height; y++) {
  345. const alpha = imageData.data[y * width * 4 + 3];
  346. if (alpha > 127 && this._sliceTop === -1) {
  347. this._sliceTop = y;
  348. continue;
  349. }
  350. if (alpha < 127 && this._sliceTop > -1) {
  351. this._sliceBottom = y;
  352. break;
  353. }
  354. }
  355. }
  356. /**
  357. * Gets or sets the internal DOM image used to render the control
  358. */
  359. public set domImage(value: HTMLImageElement) {
  360. this._domImage = value;
  361. this._loaded = false;
  362. this._imageDataCache.data = null;
  363. if (this._domImage.width) {
  364. this._onImageLoaded();
  365. } else {
  366. this._domImage.onload = () => {
  367. this._onImageLoaded();
  368. };
  369. }
  370. }
  371. public get domImage(): HTMLImageElement {
  372. return this._domImage;
  373. }
  374. private _onImageLoaded(): void {
  375. this._imageDataCache.data = null;
  376. this._imageWidth = this._domImage.width;
  377. this._imageHeight = this._domImage.height;
  378. this._loaded = true;
  379. if (this._populateNinePatchSlicesFromImage) {
  380. this._extractNinePatchSliceDataFromImage();
  381. }
  382. if (this._autoScale) {
  383. this.synchronizeSizeWithContent();
  384. }
  385. this.onImageLoadedObservable.notifyObservers(this);
  386. this._markAsDirty();
  387. }
  388. /**
  389. * Gets the image source url
  390. */
  391. @serialize()
  392. public get source() {
  393. return this._source;
  394. }
  395. /**
  396. * Gets or sets image source url
  397. */
  398. public set source(value: Nullable<string>) {
  399. if (this._source === value) {
  400. return;
  401. }
  402. this._loaded = false;
  403. this._source = value;
  404. this._imageDataCache.data = null;
  405. if (value) {
  406. value = this._svgCheck(value);
  407. }
  408. this._domImage = document.createElement("img");
  409. this._domImage.onload = () => {
  410. this._onImageLoaded();
  411. };
  412. if (value) {
  413. Tools.SetCorsBehavior(value, this._domImage);
  414. this._domImage.src = value;
  415. }
  416. }
  417. /**
  418. * Checks for svg document with icon id present
  419. */
  420. private _svgCheck(value: string): string {
  421. if (window.SVGSVGElement && value.search(/.svg#/gi) !== -1 && value.indexOf("#") === value.lastIndexOf("#")) {
  422. this._isSVG = true;
  423. var svgsrc = value.split("#")[0];
  424. var elemid = value.split("#")[1];
  425. // check if object alr exist in document
  426. var svgExist = <HTMLObjectElement>document.body.querySelector('object[data="' + svgsrc + '"]');
  427. if (svgExist) {
  428. var svgDoc = svgExist.contentDocument;
  429. // get viewbox width and height, get svg document width and height in px
  430. if (svgDoc && svgDoc.documentElement) {
  431. var vb = svgDoc.documentElement.getAttribute("viewBox");
  432. var docwidth = Number(svgDoc.documentElement.getAttribute("width"));
  433. var docheight = Number(svgDoc.documentElement.getAttribute("height"));
  434. var elem = <SVGGraphicsElement>(<unknown>svgDoc.getElementById(elemid));
  435. if (elem && vb && docwidth && docheight) {
  436. this._getSVGAttribs(svgExist, elemid);
  437. return value;
  438. }
  439. }
  440. // wait for object to load
  441. svgExist.addEventListener("load", () => {
  442. this._getSVGAttribs(svgExist, elemid);
  443. });
  444. } else {
  445. // create document object
  446. var svgImage = document.createElement("object");
  447. svgImage.data = svgsrc;
  448. svgImage.type = "image/svg+xml";
  449. svgImage.width = "0%";
  450. svgImage.height = "0%";
  451. document.body.appendChild(svgImage);
  452. // when the object has loaded, get the element attribs
  453. svgImage.onload = () => {
  454. var svgobj = <HTMLObjectElement>document.body.querySelector('object[data="' + svgsrc + '"]');
  455. if (svgobj) {
  456. this._getSVGAttribs(svgobj, elemid);
  457. }
  458. };
  459. }
  460. return svgsrc;
  461. } else {
  462. return value;
  463. }
  464. }
  465. /**
  466. * Sets sourceLeft, sourceTop, sourceWidth, sourceHeight automatically
  467. * given external svg file and icon id
  468. */
  469. private _getSVGAttribs(svgsrc: HTMLObjectElement, elemid: string) {
  470. var svgDoc = svgsrc.contentDocument;
  471. // get viewbox width and height, get svg document width and height in px
  472. if (svgDoc && svgDoc.documentElement) {
  473. var vb = svgDoc.documentElement.getAttribute("viewBox");
  474. var docwidth = Number(svgDoc.documentElement.getAttribute("width"));
  475. var docheight = Number(svgDoc.documentElement.getAttribute("height"));
  476. // get element bbox and matrix transform
  477. var elem = svgDoc.getElementById(elemid) as Nullable<SVGGraphicsElement>;
  478. if (vb && docwidth && docheight && elem) {
  479. var vb_width = Number(vb.split(" ")[2]);
  480. var vb_height = Number(vb.split(" ")[3]);
  481. var elem_bbox = elem.getBBox();
  482. var elem_matrix_a = 1;
  483. var elem_matrix_d = 1;
  484. var elem_matrix_e = 0;
  485. var elem_matrix_f = 0;
  486. if (elem.transform && elem.transform.baseVal.consolidate()) {
  487. elem_matrix_a = elem.transform.baseVal.consolidate().matrix.a;
  488. elem_matrix_d = elem.transform.baseVal.consolidate().matrix.d;
  489. elem_matrix_e = elem.transform.baseVal.consolidate().matrix.e;
  490. elem_matrix_f = elem.transform.baseVal.consolidate().matrix.f;
  491. }
  492. // compute source coordinates and dimensions
  493. this.sourceLeft = ((elem_matrix_a * elem_bbox.x + elem_matrix_e) * docwidth) / vb_width;
  494. this.sourceTop = ((elem_matrix_d * elem_bbox.y + elem_matrix_f) * docheight) / vb_height;
  495. this.sourceWidth = elem_bbox.width * elem_matrix_a * (docwidth / vb_width);
  496. this.sourceHeight = elem_bbox.height * elem_matrix_d * (docheight / vb_height);
  497. this._svgAttributesComputationCompleted = true;
  498. this.onSVGAttributesComputedObservable.notifyObservers(this);
  499. }
  500. }
  501. }
  502. /**
  503. * Gets or sets the cell width to use when animation sheet is enabled
  504. * @see https://doc.babylonjs.com/how_to/gui#image
  505. */
  506. get cellWidth(): number {
  507. return this._cellWidth;
  508. }
  509. set cellWidth(value: number) {
  510. if (this._cellWidth === value) {
  511. return;
  512. }
  513. this._cellWidth = value;
  514. this._markAsDirty();
  515. }
  516. /**
  517. * Gets or sets the cell height to use when animation sheet is enabled
  518. * @see https://doc.babylonjs.com/how_to/gui#image
  519. */
  520. get cellHeight(): number {
  521. return this._cellHeight;
  522. }
  523. set cellHeight(value: number) {
  524. if (this._cellHeight === value) {
  525. return;
  526. }
  527. this._cellHeight = value;
  528. this._markAsDirty();
  529. }
  530. /**
  531. * Gets or sets the cell id to use (this will turn on the animation sheet mode)
  532. * @see https://doc.babylonjs.com/how_to/gui#image
  533. */
  534. get cellId(): number {
  535. return this._cellId;
  536. }
  537. set cellId(value: number) {
  538. if (this._cellId === value) {
  539. return;
  540. }
  541. this._cellId = value;
  542. this._markAsDirty();
  543. }
  544. /**
  545. * Creates a new Image
  546. * @param name defines the control name
  547. * @param url defines the image url
  548. */
  549. constructor(public name?: string, url: Nullable<string> = null) {
  550. super(name);
  551. this.source = url;
  552. }
  553. /**
  554. * Tests if a given coordinates belong to the current control
  555. * @param x defines x coordinate to test
  556. * @param y defines y coordinate to test
  557. * @returns true if the coordinates are inside the control
  558. */
  559. public contains(x: number, y: number): boolean {
  560. if (!super.contains(x, y)) {
  561. return false;
  562. }
  563. if (!this._detectPointerOnOpaqueOnly || !this._workingCanvas) {
  564. return true;
  565. }
  566. const width = this._currentMeasure.width | 0;
  567. const height = this._currentMeasure.height | 0;
  568. const key = width + "_" + height;
  569. let imageData = this._imageDataCache.data;
  570. if (!imageData || this._imageDataCache.key !== key) {
  571. const canvas = this._workingCanvas;
  572. const context = canvas.getContext("2d")!;
  573. this._imageDataCache.data = imageData = context.getImageData(0, 0, width, height).data;
  574. this._imageDataCache.key = key;
  575. }
  576. x = (x - this._currentMeasure.left) | 0;
  577. y = (y - this._currentMeasure.top) | 0;
  578. const pickedPixel = imageData[(x + y * width) * 4 + 3];
  579. return pickedPixel > 0;
  580. }
  581. protected _getTypeName(): string {
  582. return "Image";
  583. }
  584. /** Force the control to synchronize with its content */
  585. public synchronizeSizeWithContent() {
  586. if (!this._loaded) {
  587. return;
  588. }
  589. this.width = this._domImage.width + "px";
  590. this.height = this._domImage.height + "px";
  591. }
  592. protected _processMeasures(parentMeasure: Measure, context: CanvasRenderingContext2D): void {
  593. if (this._loaded) {
  594. switch (this._stretch) {
  595. case Image.STRETCH_NONE:
  596. break;
  597. case Image.STRETCH_FILL:
  598. break;
  599. case Image.STRETCH_UNIFORM:
  600. break;
  601. case Image.STRETCH_NINE_PATCH:
  602. break;
  603. case Image.STRETCH_EXTEND:
  604. if (this._autoScale) {
  605. this.synchronizeSizeWithContent();
  606. }
  607. if (this.parent && this.parent.parent) {
  608. // Will update root size if root is not the top root
  609. this.parent.adaptWidthToChildren = true;
  610. this.parent.adaptHeightToChildren = true;
  611. }
  612. break;
  613. }
  614. }
  615. super._processMeasures(parentMeasure, context);
  616. }
  617. private _prepareWorkingCanvasForOpaqueDetection() {
  618. if (!this._detectPointerOnOpaqueOnly) {
  619. return;
  620. }
  621. if (!this._workingCanvas) {
  622. this._workingCanvas = document.createElement("canvas");
  623. }
  624. const canvas = this._workingCanvas;
  625. const width = this._currentMeasure.width;
  626. const height = this._currentMeasure.height;
  627. const context = canvas.getContext("2d")!;
  628. canvas.width = width;
  629. canvas.height = height;
  630. context.clearRect(0, 0, width, height);
  631. }
  632. private _drawImage(context: CanvasRenderingContext2D, sx: number, sy: number, sw: number, sh: number, tx: number, ty: number, tw: number, th: number) {
  633. context.drawImage(this._domImage, sx, sy, sw, sh, tx, ty, tw, th);
  634. if (!this._detectPointerOnOpaqueOnly) {
  635. return;
  636. }
  637. const canvas = this._workingCanvas!;
  638. context = canvas.getContext("2d")!;
  639. context.drawImage(this._domImage, sx, sy, sw, sh, tx - this._currentMeasure.left, ty - this._currentMeasure.top, tw, th);
  640. }
  641. public _draw(context: CanvasRenderingContext2D): void {
  642. context.save();
  643. if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
  644. context.shadowColor = this.shadowColor;
  645. context.shadowBlur = this.shadowBlur;
  646. context.shadowOffsetX = this.shadowOffsetX;
  647. context.shadowOffsetY = this.shadowOffsetY;
  648. }
  649. let x, y, width, height;
  650. if (this.cellId == -1) {
  651. x = this._sourceLeft;
  652. y = this._sourceTop;
  653. width = this._sourceWidth ? this._sourceWidth : this._imageWidth;
  654. height = this._sourceHeight ? this._sourceHeight : this._imageHeight;
  655. } else {
  656. let rowCount = this._domImage.naturalWidth / this.cellWidth;
  657. let column = (this.cellId / rowCount) >> 0;
  658. let row = this.cellId % rowCount;
  659. x = this.cellWidth * row;
  660. y = this.cellHeight * column;
  661. width = this.cellWidth;
  662. height = this.cellHeight;
  663. }
  664. this._prepareWorkingCanvasForOpaqueDetection();
  665. this._applyStates(context);
  666. if (this._loaded) {
  667. switch (this._stretch) {
  668. case Image.STRETCH_NONE:
  669. this._drawImage(context, x, y, width, height, this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
  670. break;
  671. case Image.STRETCH_FILL:
  672. this._drawImage(context, x, y, width, height, this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
  673. break;
  674. case Image.STRETCH_UNIFORM:
  675. var hRatio = this._currentMeasure.width / width;
  676. var vRatio = this._currentMeasure.height / height;
  677. var ratio = Math.min(hRatio, vRatio);
  678. var centerX = (this._currentMeasure.width - width * ratio) / 2;
  679. var centerY = (this._currentMeasure.height - height * ratio) / 2;
  680. this._drawImage(context, x, y, width, height, this._currentMeasure.left + centerX, this._currentMeasure.top + centerY, width * ratio, height * ratio);
  681. break;
  682. case Image.STRETCH_EXTEND:
  683. this._drawImage(context, x, y, width, height, this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height);
  684. break;
  685. case Image.STRETCH_NINE_PATCH:
  686. this._renderNinePatch(context);
  687. break;
  688. }
  689. }
  690. context.restore();
  691. }
  692. private _renderNinePatch(context: CanvasRenderingContext2D): void {
  693. const leftWidth = this._sliceLeft;
  694. const topHeight = this._sliceTop;
  695. const bottomHeight = this._imageHeight - this._sliceBottom;
  696. const rightWidth = this._imageWidth - this._sliceRight;
  697. const centerWidth = this._sliceRight - this._sliceLeft;
  698. const centerHeight = this._sliceBottom - this._sliceTop;
  699. const targetCenterWidth = (this._currentMeasure.width - rightWidth - leftWidth) + 2;
  700. const targetCenterHeight = (this._currentMeasure.height - bottomHeight - topHeight) + 2;
  701. const centerLeftOffset = this._currentMeasure.left + leftWidth - 1;
  702. const centerTopOffset = this._currentMeasure.top + topHeight - 1;
  703. const rightOffset = this._currentMeasure.left + this._currentMeasure.width - rightWidth;
  704. const bottomOffset = this._currentMeasure.top + this._currentMeasure.height - bottomHeight;
  705. //Top Left
  706. this._drawImage(context, 0, 0, leftWidth, topHeight, this._currentMeasure.left, this._currentMeasure.top, leftWidth, topHeight);
  707. //Top
  708. this._drawImage(context, this._sliceLeft, 0, centerWidth, topHeight, centerLeftOffset, this._currentMeasure.top, targetCenterWidth, topHeight);
  709. //Top Right
  710. this._drawImage(context, this.sliceRight, 0, rightWidth, topHeight, rightOffset, this._currentMeasure.top, rightWidth, topHeight);
  711. //Left
  712. this._drawImage(context, 0, this._sliceTop, leftWidth, centerHeight, this._currentMeasure.left, centerTopOffset, leftWidth, targetCenterHeight);
  713. // Center
  714. this._drawImage(context, this._sliceLeft, this._sliceTop, centerWidth, centerHeight, centerLeftOffset, centerTopOffset, targetCenterWidth, targetCenterHeight);
  715. //Right
  716. this._drawImage(context, this._sliceRight, this._sliceTop, rightWidth, centerHeight, rightOffset, centerTopOffset, rightWidth, targetCenterHeight);
  717. //Bottom Left
  718. this._drawImage(context, 0, this._sliceBottom, leftWidth, bottomHeight, this._currentMeasure.left, bottomOffset, leftWidth, bottomHeight);
  719. //Bottom
  720. this._drawImage(context, this.sliceLeft, this._sliceBottom, centerWidth, bottomHeight, centerLeftOffset, bottomOffset, targetCenterWidth, bottomHeight);
  721. //Bottom Right
  722. this._drawImage(context, this._sliceRight, this._sliceBottom, rightWidth, bottomHeight, rightOffset, bottomOffset, rightWidth, bottomHeight);
  723. }
  724. public dispose() {
  725. super.dispose();
  726. this.onImageLoadedObservable.clear();
  727. this.onSVGAttributesComputedObservable.clear();
  728. }
  729. // Static
  730. /** STRETCH_NONE */
  731. public static readonly STRETCH_NONE = 0;
  732. /** STRETCH_FILL */
  733. public static readonly STRETCH_FILL = 1;
  734. /** STRETCH_UNIFORM */
  735. public static readonly STRETCH_UNIFORM = 2;
  736. /** STRETCH_EXTEND */
  737. public static readonly STRETCH_EXTEND = 3;
  738. /** NINE_PATCH */
  739. public static readonly STRETCH_NINE_PATCH = 4;
  740. }
  741. _TypeStore.RegisteredTypes["BABYLON.GUI.Image"] = Image;