diff --git a/src/js/stendhal/sprite/image/HTMLImageElementUtil.ts b/src/js/stendhal/sprite/image/HTMLImageElementUtil.ts index 134e2f835e..e8d492de20 100644 --- a/src/js/stendhal/sprite/image/HTMLImageElementUtil.ts +++ b/src/js/stendhal/sprite/image/HTMLImageElementUtil.ts @@ -9,6 +9,7 @@ * * ***************************************************************************/ +import { ImageWithDimensions } from "data/ImageWithDimensions"; import { store } from "../../data/SpriteStore"; export class HTMLImageElementUtil { @@ -19,39 +20,37 @@ export class HTMLImageElementUtil { * Otherwise a copy of the image data is returned. This is meant * to be used for obtaining the drag image for drag and drop. * + * This method intentionally returns an HTMLImageElement because Chrome is + * not able to use an HTMLCanvasElement as drag image. Firefox does support + * this. But neither browser is able to use an ImageBitmap. + * * @param image original image * @param width width of the area * @param height height of the area * @param {number=} offsetX optional. left x coordinate of the area * @param {number=} offsetY optional. top y coordinate of the area */ - static getAreaOf(image: HTMLImageElement, width: number, height: number, + static getAreaOf(image: CanvasImageSource & ImageWithDimensions, width: number, height: number, offsetX?: number, offsetY?: number): any { - try { - offsetX = offsetX || 0; - offsetY = offsetY || 0; - if ((image.width === width) && (image.height === height) - && (offsetX === 0) && (offsetY === 0)) { - return image; - } - var canvas = document.createElement("canvas") as HTMLCanvasElement; - canvas.width = width; - canvas.height = height; - var ctx = canvas.getContext("2d")!; - ctx.drawImage(image, offsetX, offsetY, width, height, 0, 0, width, height); - // Firefox would be able to use the canvas directly as a drag image, but - // Chrome does not. This should work in any standards compliant browser. - // TODO: Check if that is still true - var newImage = new Image(); - newImage.src = canvas.toDataURL("image/png"); - return newImage; - } catch (err) { - if (err instanceof DOMException) { - return store.getFailsafe(); - } else { - // don't ignore other errors - throw err; - } + + offsetX = offsetX || 0; + offsetY = offsetY || 0; + if (image instanceof HTMLImageElement + && (image.width === width) && (image.height === height) + && (offsetX === 0) && (offsetY === 0)) { + return image; } + let canvas = document.createElement("canvas") as HTMLCanvasElement; + canvas.width = width; + canvas.height = height; + let ctx = canvas.getContext("2d", {willReadFrequently: true})!; + try { + ctx.drawImage(image, offsetX, offsetY, width, height, 0, 0, width, height); + } catch (err) { + ctx.drawImage(store.getFailsafe(), 0, 0); + } + let newImage = new Image(); + newImage.src = canvas.toDataURL("image/png"); + return newImage; } }