* Generates a real canvas element, with the image draw into if there is one. * @param {object} [options] The available options. * @param {number} [options.width] The width of the canvas. * @param {number} [options.height] The height of the canvas. * @param {Function} [options.beforeDraw]
(options?: {
width?: number;
height?: number;
beforeDraw?: (context: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => void;
})
| 492 | * @returns {Promise} Returns a promise that resolves to the generated canvas element. |
| 493 | */ |
| 494 | $toCanvas(options?: { |
| 495 | width?: number; |
| 496 | height?: number; |
| 497 | beforeDraw?: (context: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => void; |
| 498 | }): Promise<HTMLCanvasElement> { |
| 499 | return new Promise<HTMLCanvasElement>((resolve, reject) => { |
| 500 | if (!this.isConnected) { |
| 501 | reject(new Error('The current element is not connected to the DOM.')); |
| 502 | return; |
| 503 | } |
| 504 | |
| 505 | const canvas = document.createElement('canvas'); |
| 506 | let width = this.offsetWidth; |
| 507 | let height = this.offsetHeight; |
| 508 | let scale = 1; |
| 509 | |
| 510 | if (isPlainObject(options) |
| 511 | && (isPositiveNumber(options.width) || isPositiveNumber(options.height))) { |
| 512 | ({ width, height } = getAdjustedSizes({ |
| 513 | aspectRatio: width / height, |
| 514 | width: options.width as number, |
| 515 | height: options.height as number, |
| 516 | })); |
| 517 | scale = width / this.offsetWidth; |
| 518 | } |
| 519 | |
| 520 | canvas.width = width; |
| 521 | canvas.height = height; |
| 522 | |
| 523 | const cropperImage: any = this.querySelector(this.$getTagNameOf(CROPPER_IMAGE)); |
| 524 | |
| 525 | if (!cropperImage) { |
| 526 | resolve(canvas); |
| 527 | return; |
| 528 | } |
| 529 | |
| 530 | cropperImage.$ready().then((image: HTMLImageElement) => { |
| 531 | const context = canvas.getContext('2d'); |
| 532 | |
| 533 | if (context) { |
| 534 | const [a, b, c, d, e, f] = cropperImage.$getTransform(); |
| 535 | let newE = e; |
| 536 | let newF = f; |
| 537 | let destWidth = image.naturalWidth; |
| 538 | let destHeight = image.naturalHeight; |
| 539 | |
| 540 | if (scale !== 1) { |
| 541 | newE *= scale; |
| 542 | newF *= scale; |
| 543 | destWidth *= scale; |
| 544 | destHeight *= scale; |
| 545 | } |
| 546 | |
| 547 | const centerX = destWidth / 2; |
| 548 | const centerY = destHeight / 2; |
| 549 | |
| 550 | context.fillStyle = 'transparent'; |
| 551 | context.fillRect(0, 0, width, height); |
no test coverage detected