<canvas id='master' width='100' height='100'></canvas>
<canvas id='pid' width='100' height='100'></canvas>
<canvas id='di' width='100' height='100'></canvas>
<canvas id='rect' width='100' height='100'></canvas>
var master = document.getElementById('master');
var masterctx = master.getContext('2d');
var pid = document.getElementById('pid').getContext('2d');
var di = document.getElementById('di').getContext('2d');
var rect = document.getElementById('rect').getContext('2d');
masterctx.fillRect(0,0,50,50);
masterctx.fillStyle = "red";
masterctx.fillRect(50,50,100,100);
di.drawImage(master,0,0);
let imgData = masterctx.getImageData(0,0,100,100);
pid.putImageData(imgData,0,0);
di.drawImage(master,25,0,50,100,25,0,50,100);
let imgData = masterctx.getImageData(25,0,75,100);
pid.putImageData(imgData,25,0);
rect.fillRect(0,0,50,50);
rect.fillStyle = "red";
rect.fillRect(50,50,100,100);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
DrawImage whole master into di canvas | |
PutImageData whole master into pid canvas | |
DrawImage half master into di canvas | |
PutImageData half master into pid canvas | |
rect |
Test name | Executions per second |
---|---|
DrawImage whole master into di canvas | 463711.9 Ops/sec |
PutImageData whole master into pid canvas | 3924.8 Ops/sec |
DrawImage half master into di canvas | 410366.0 Ops/sec |
PutImageData half master into pid canvas | 2416.3 Ops/sec |
rect | 1756976.5 Ops/sec |
Let's dive into the details of this benchmark.
What is being tested?
The benchmark compares three different methods for drawing an image onto another HTML canvas element:
drawImage()
method, which draws an entire image or a region of an image onto a canvas.putImageData()
method, which puts an ImageData object (a pixel-by-pixel representation of an image) onto a canvas.fillRect()
method, which simply fills a rectangular area with a solid color.What options are compared?
The benchmark tests the following scenarios:
drawImage()
.drawImage()
(by specifying only part of the image coordinates).putImageData()
, which includes:Pros and Cons:
putImageData()
for small images or simple graphics.Library and Special JS Feature/Syntax:
None mentioned in this benchmark.
Other Considerations:
drawImage()
method uses the 2D canvas context (ctx
), while putImageData()
uses a separate ImageData object.drawImage()
with a canvas may be more efficient.Alternative approaches:
If you need to draw images onto canvases frequently:
drawImage()
for large images or complex graphics.fillRect()
or other basic canvas methods when possible.Keep in mind that the best approach depends on your specific requirements and performance needs. This benchmark provides a good starting point to evaluate these options.