While drawing bitmap image onto off-screen canvas, Chrome console threw an error on me:
Failed to execute 'getContext' on 'OffscreenCanvas': The provided value 'bitmaprenderer' is not a valid enum value of type OffscreenRenderingContextType.
The problem occurs in both worker and window contexts:
var img = new Image(63, 177);
img.src = "https://cdn.sstatic.net/Img/unified/sprites.svg";
img.onload = _ => {
createImageBitmap(img).then(bitmap => {
var canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
canvas.getContext('bitmaprenderer');
}).catch(e => console.error(e.message));
};
I can get this canvas context type in window context while using (on-screen) canvas interface as so:
document.createElement('canvas').getContext('bitmaprenderer');
The canvas context is needed in worker, so I can't use (on-screen) canvas interface, there is no document access after all.
While I can just get two-dimensional rendering context of bitmap image by using '2d' identifier in getContext method, it would be OffscreenCanvasRenderingContext2D and not ImageBitmapRenderingContext. I don't know the difference in latency for both interfaces, but as far as I understand, bitmap can be transferred onto canvas immediately, while 2d context should be drawn.
My Chrome version is 74.0.3729.169, and linked article browser compatibility table stipulates, that bitmap rendering context interface is available from 66 version.
Am I doing something wrong, or is bitmaprenderer not supported as a valid value for off-screen canvas rendering context as of now? How can I access bitmap rendering context for off-screen canvas in Chrome? Thanks in advance.
Yes, at the time this question was asked ImageBitmapRenderingContext was still not available from an OffscreenCanvas
, it now is but Chrome has a bug which prevents it from rendering to a placeholder canvas.
Note that if you wanted to use this bitmap-renderer for something like being able to draw it to another context, then you could directly pass the ImageBitmap
to either 2D drawImage or webgl texImage2d
.
Also note that in your case, since you are in the main thread and not in a Worker
, you absolutely don't need an OffscreenCanvas
and can just do
var img = new Image();
img.crossOrigin = 'anonymous';
img.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Fiore_con_petali_arancioni_SVG.svg";
img.onload = _ => {
createImageBitmap(img)
.then(bitmap => {
const canvas = Object.assign(document.createElement('canvas'), {
width: bitmap.width,
height: bitmap.height
});
const ctx = canvas.getContext('bitmaprenderer');
ctx.transferFromImageBitmap(bitmap);
return new Promise((res, rej) => {
canvas.toBlob(blob => {
if (!blob) rej('error');
res(blob);
});
});
})
.then(blob => {
console.log(blob);
result.src = URL.createObjectURL(blob);
})
.catch(e => console.error(e.message));
};
PNG: <img id="result">