var img = new Image();
var imageBitmap;
var doneLoading = false;
let canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 480;
let canvas2 = document.createElement('canvas');
let offscreen = canvas2.transferControlToOffscreen();
offscreen.width = 640;
offscreen.height = 480;
var ctx = canvas.getContext('2d');
var ctx2 = offscreen.getContext('2d');
img.addEventListener('load', function() {
Promise.all([
createImageBitmap(img)
]).then(function(images) {
imageBitmap = images[0];
doneLoading = true;
}, false);
});
img.src = 'https://media.discordapp.net/attachments/447410261289205781/574359442913492992/unknown.png';
if (doneLoading)
{
ctx.clearRect(0,0,640,480);
ctx.drawImage(imageBitmap,0,0);
}
if (doneLoading)
{
ctx2.clearRect(0,0,640,480);
ctx2.drawImage(imageBitmap,0,0);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Canvas | |
OffscreenCanvas |
Test name | Executions per second |
---|---|
Canvas | 134459424.0 Ops/sec |
OffscreenCanvas | 129154992.0 Ops/sec |
I'll provide an explanation of the benchmark, its options, pros and cons, and other considerations.
Benchmark Overview
The benchmark measures the performance of two approaches to render images on a 480x640 pixel canvas: Canvas
and OffscreenCanvas
. The goal is to clear the canvas, draw the image, and then display it.
Options Compared
There are two options being compared:
ctx
) of the canvas element.offscreen
), transfers control to it, and renders the image on that offscreen canvas using its own rendering context (ctx2
). The resulting offscreen canvas is then transferred back to the original canvas element.Pros and Cons of Each Approach
Other Considerations
createImageBitmap
function from the Web APIs, which is a standardized API for working with image bitmaps in web applications. This library provides a convenient way to manipulate images and is widely supported across browsers.Alternatives
If you're interested in exploring alternative approaches, here are some options:
Keep in mind that these alternatives may introduce additional complexity or dependencies compared to the original Canvas and OffscreenCanvas approaches.