Make createCanvasContext2D work in non-window context

This commit is contained in:
Andreas Hocevar
2020-03-04 16:02:07 +01:00
parent f896d9fb03
commit 717b8ad0cf

View File

@@ -3,6 +3,7 @@
*/
//FIXME Move this function to the canvas module
/**
* Create an html canvas element and returns its 2d context.
* @param {number=} opt_width Canvas width.
@@ -12,14 +13,18 @@
*/
export function createCanvasContext2D(opt_width, opt_height, opt_canvasPool) {
const canvas = opt_canvasPool && opt_canvasPool.length ?
opt_canvasPool.shift() : document.createElement('canvas');
opt_canvasPool.shift() :
'document' in self ?
document.createElement('canvas') :
new OffscreenCanvas(opt_width || 300, opt_height || 300);
if (opt_width) {
canvas.width = opt_width;
}
if (opt_height) {
canvas.height = opt_height;
}
return canvas.getContext('2d');
//FIXME Allow OffscreenCanvasRenderingContext2D as return type
return /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'));
}