<canvas id="canvas" width="400" height="400"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var cacheG = document.createElement('canvas');
var cacheD = cacheG.getContext('2d');
cacheG.width = 12;
cacheG.height = 12;
cacheD.beginPath();
cacheD.fillStyle = '#000';
cacheD.arc(6, 6, 6, 0, Math.PI * 2, true);
cacheD.fill();
var d = cacheD.getImageData(0,0,12,12)
ctx.drawImage(cacheG, 6, 6);
ctx.putImageData(d, 6, 6);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
drawImage | |
putImageData |
Test name | Executions per second |
---|---|
drawImage | 700736.4 Ops/sec |
putImageData | 28590.9 Ops/sec |
I'll break down the provided benchmark definition and test cases, explaining what's being tested, compared options, pros and cons of each approach, and other considerations.
Benchmark Definition
The benchmark is designed to compare the performance of two approaches for drawing an image on a canvas element: drawImage
and putImageData
. The benchmark creates a small grayscale image (cacheG
) and retrieves its pixel data using getImageData
.
Script Preparation Code
This code sets up the environment:
canvas
element (var canvas = document.getElementById('canvas');
) and gets its 2D drawing context (var ctx = canvas.getContext("2d");
).canvas
element as a cache (var cacheG = document.createElement('canvas');
) with a fixed size of 12x12 pixels.var cacheD = cacheG.getContext('2d');
).cacheD.beginPath()
, cacheD.fillStyle
, and cacheD.arc()
methods.cacheD.getImageData(0, 0, 12, 12)
.Html Preparation Code
This code sets up the HTML environment:
<canvas id="canvas" width="400" height="400"></canvas>
The canvas element is used to render the benchmark results.
Individual Test Cases
There are two test cases:
ctx.drawImage(cacheG, 6, 6);
.ctx.putImageData(d, 6, 6);
.Options Compared
Both approaches compare the execution time of drawing an image on a canvas element:
getImageData
and then draws it onto the canvas using the same 2D drawing context.Pros and Cons of Each Approach
Other Considerations
cacheG
) to minimize the impact of image size on the results. This allows for a more focused comparison between drawImage
and putImageData
.Other Alternatives
If the benchmark were to be modified or expanded upon:
drawImage
and putImageData
.createRGBCanvas
or fillRect
, could provide a more comprehensive understanding of the performance characteristics of each approach.drawImage
and putImageData
.