var img = new Image();
var imageBitmap;
var doneLoading = false;
var canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 480;
var canvas2 = document.createElement('canvas');
canvas2.width = 640;
canvas2.height = 480;
var ctx = canvas.getContext('2d');
var ctx2 = canvas2.getContext('2d');
img.addEventListener('load', function() {
Promise.all([
createImageBitmap(img)
]).then(function(images) {
imageBitmap = images[0];
doneLoading = true;
}, false);
});
if (doneLoading) {
ctx.drawImage(img,0,0)
}
img.src = 'https://1.bp.blogspot.com/-52MtzD0GfX0/WvP52CL1WjI/AAAAAAAAOVw/_OpK4JHeWK01d-7IiZ6vzojYGhXqLRXrACLcBGAs/s1600/EMxediL.jpg';
if (doneLoading)
ctx2.drawImage(canvas,0,0);
if (doneLoading)
ctx2.drawImage(imageBitmap,0,0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Canvas Image | |
Image Bitmap |
Test name | Executions per second |
---|---|
Canvas Image | 444672.1 Ops/sec |
Image Bitmap | 416270.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches to rendering images: using a Canvas element with a 2D drawing context (ctx
) versus using an ImageBitmap API (createImageBitmap
).
Options Compared
Two options are compared:
ctx.drawImage()
method to draw the image on the canvas.imageBitmap
returned by createImageBitmap()
and passes it to ctx2.drawImage()
.Pros and Cons of Each Approach
Library/Technology Used
createImageBitmap()
function is part of the W3C specification for the Web APIs, which provides a modern and optimized way to work with images. It's supported by most modern browsers.Special JS Feature/Syntax
The benchmark uses the Promise.all()
method, which is a modern JavaScript feature introduced in ECMAScript 2015 (ES6). This method allows for parallel execution of multiple promises, making it useful for async operations like loading images.
Other Considerations
doneLoading
flag is used to synchronize the drawing operations on both canvases, ensuring that they are executed after the image has loaded.Alternatives
If you want to replicate this benchmark or explore similar optimizations, consider using other libraries or APIs for working with images in JavaScript. Some alternatives include:
Keep in mind that each alternative has its own strengths and weaknesses, and the choice of library or API will depend on your specific use case and requirements.