<canvas align="center" id="canvas" width="800" height="800"></canvas>
var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = 'rgba(0,1,0,1)';
var rects = []
for (var i = 0; i < 50; i++) {
var width = 5 + i * 5;
var height = 7 + i * 3;
var path = new Path2D();
path.rect(0, 0, width, height);
var rect =
{
x: i,
y: i,
width: width,
height: height,
cachedPath: path
};
rects.push(rect);
}
ctx.clearRect(0, 0, 500, 500);
for (var i = 0; i < rects.length; i++) {
var rect = rects[i];
ctx.rect(rect.x, rect.y, rect.width, rect.height);
ctx.fill();
}
for (var i = 0; i < rects.length; i++) {
var rect = rects[i];
var path = new Path2D();
path.rect(rect.x, rect.y, rect.width, rect.height)
ctx.fill(path)
}
for (var i = 0; i < rects.length; i++) {
var rect = rects[i];
ctx.translate(rect.x, rect.y);
ctx.fill(rect.path);
ctx.translate(-rect.x, -rect.y);
}
for (var i = 0; i < rects.length; i++) {
var rect = rects[i];
ctx.beginPath();
ctx.rect(rect.x, rect.y, rect.width, rect.height);
ctx.fill();
}
for (var i = 0; i < rects.length; i++) {
var rect = rects[i];
ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Direct draw | |
New path | |
Cached path | |
Direct with beginpath | |
Direct fillrect |
Test name | Executions per second |
---|---|
Direct draw | 130.9 Ops/sec |
New path | 14718.2 Ops/sec |
Cached path | 30501.3 Ops/sec |
Direct with beginpath | 17044.2 Ops/sec |
Direct fillrect | 26224.7 Ops/sec |
Overview
The provided JSON represents a JavaScript microbenchmark for measuring the performance of different drawing approaches in HTML5 Canvas. The benchmark creates a canvas with 50 rectangles and then draws each rectangle using various methods, such as direct draw, new path, cached path, direct with beginpath, and direct fillrect.
Test Cases
Each test case measures the performance of a specific drawing approach:
Library:
Path2D
is used in the benchmark code. It's a built-in JavaScript API for working with paths in HTML5 Canvas.Special JS Features/Syntax:
None explicitly mentioned.
Options Compared:
The benchmark compares five different drawing approaches:
ctx.rect()
and ctx.fill()
new Path2D()
and then path.rect()
followed by ctx.fill(path)
cachedPath
property of the rectangle object and then ctx.fill(cachedPath)
ctx.beginPath()
before drawing each rectanglectx.fillRect()
Pros and Cons:
Other Alternatives:
ctx.globalAlpha
and ctx.globalCompositeOperation
to optimize drawing performance.Please note that the best approach depends on the specific use case, hardware, and requirements. This benchmark provides a general idea of how different drawing approaches compare in terms of performance.