var img = new Image();
img.decoding = 'sync';
var imageBitmap;
var imageBitmapResized;
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);
Promise.all([
createImageBitmap(img, {imageOrientation: "none", premultiplyAlpha: "none", resizeWidth:~~(img.width/2), resizeHeight:~~(img.height/2), resizeQuality:"low"})
]).then(function(images) {
imageBitmapResized = images[0];
doneLoading = true;
}, false);
});
img.src = 'https://media.discordapp.net/attachments/447410261289205781/574359442913492992/unknown.png';
if (doneLoading)
ctx.drawImage(img,0,0);
if (doneLoading)
ctx.drawImage(imageBitmap,0,0);
if (doneLoading)
ctx.drawImage(imageBitmapResized,0,0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Image | |
ImageBitmap/Offscreen | |
ImageBitmap/Offscreen Resized |
Test name | Executions per second |
---|---|
Image | 160476400.0 Ops/sec |
ImageBitmap/Offscreen | 171451520.0 Ops/sec |
ImageBitmap/Offscreen Resized | 156561392.0 Ops/sec |
I'll break down what's being tested in the provided benchmark, explain the options compared, and discuss their pros and cons.
What is being tested?
The benchmark measures the performance of drawing images using different approaches:
Image
test case).ImageBitmap
from the original image and drawing it on an offscreen canvas (ImageBitmap/Offscreen
test case).ImageBitmap
from the original image and drawing it on another offscreen canvas (ImageBitmap/Offscreen Resized
test case).Options compared:
The benchmark compares three approaches:
ctx.drawImage(img, 0, 0)
.ImageBitmap
from the original image and drawing it on an offscreen canvas using ctx.drawImage(imageBitmap, 0, 0)
.ImageBitmap
from the original image and drawing it on another offscreen canvas using ctx.drawImage(imageBitmapResized, 0, 0)
.Pros and Cons of each approach:
ImageBitmap
object, which may add overhead.ImageBitmap
object, which adds additional complexity.Other considerations:
Promise.all
calls and canvas elements being created. This complexity may not be necessary for this specific benchmark.Alternative approaches:
Other alternatives to consider when drawing images in JavaScript include:
Canvas
API with the webp
format.Keep in mind that each approach has its own strengths and weaknesses, and the best choice depends on the specific requirements of your project.