<canvas id='master' width='100' height='100'></canvas>
<canvas id='pid' width='100' height='100'></canvas>
<canvas id='di' 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');
masterctx.fillRect(0,0,50,50);
masterctx.fillStyle = "red";
masterctx.fillRect(50,50,100,100);
var idfull = masterctx.getImageData(0, 0, 100, 100);
var idhalf = masterctx.getImageData(25,0,75,100);
di.drawImage(master,0,0);
pid.putImageData(idfull,0,0);
di.drawImage(master,25,0,50,100,25,0,50,100);
pid.putImageData(idhalf,25,0);
--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 |
Test name | Executions per second |
---|---|
DrawImage whole master into di canvas | 690693.8 Ops/sec |
PutImageData whole master into pid canvas | 356884.2 Ops/sec |
DrawImage half master into di canvas | 244296.7 Ops/sec |
PutImageData half master into pid canvas | 451423.2 Ops/sec |
The benchmark defined in the provided JSON assesses the performance differences between two methods for rendering images onto HTML canvas elements in JavaScript: putImageData
and drawImage
. This comparison focuses on how to transfer pixel data from one canvas to another and evaluates their efficiency in various scenarios.
DrawImage Method:
di.drawImage(master,0,0);
di.drawImage(master,25,0,50,100,25,0,50,100);
PutImageData Method:
pid.putImageData(idfull,0,0);
pid.putImageData(idhalf,25,0);
The benchmark is executed in the context of the HTML5 <canvas>
API, which allows for digitally drawing graphics via JavaScript. The getContext('2d')
method is utilized to obtain the rendering context, which provides methods for drawing shapes, text, images, and manipulating pixel data on the canvas.
Pros:
drawImage
is optimized internally by the browser, making it faster for straightforward image transfers.Cons:
Pros:
Cons:
drawImage
as it requires copying pixel data to and from a ImageData
object. This can involve additional overhead, especially for larger images, since the data is handled at the pixel level.The benchmark results indicate the following performance in terms of executions per second for each test case:
From the results, it's evident that for the specific test scenarios, drawImage
significantly outperforms putImageData
in both whole and half operations, highlighting its optimization for rapid drawing tasks.
In addition to the tested methods (drawImage and putImageData), alternatives for image rendering might include:
Choosing between these methods depends on the use case, the need for performance optimization, and the level of control required over the pixel data being drawn.