<canvas id="c" width="800" height="1"></canvas>
$N = 800;
$c = document.getElementById('c');
$ctx = c.getContext('2d');
$ctx.clearRect(0, 0, $N, 1);
$pxls = [];
for (let i = 0; i < $N; ++i) {
$pxls.push({
r: Math.random() * 255 << 0,
g: Math.random() * 255 << 0,
b: Math.random() * 255 << 0
});
}
for (let i = 0; i < $N; i++) {
let px = $pxls[i];
$ctx.fillStyle = 'rgb(' + px.r + ',' + px.g + ',' + px.b + ')';
$ctx.fillRect(i, 0, 1, 1);
}
const imageData = $ctx.createImageData($N, 1);
const data = imageData.data;
for (let i = 0; i < $N; i++) {
let px = $pxls[i];
data[i * $N * 4 + 0] = px.r;
data[i * $N * 4 + 1] = px.g;
data[i * $N * 4 + 2] = px.b;
data[i * $N * 4 + 3] = 255;
}
$ctx.putImageData(imageData, 0, 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
FillRect | |
PutImageData |
Test name | Executions per second |
---|---|
FillRect | 1105.9 Ops/sec |
PutImageData | 2918.4 Ops/sec |
What is being tested?
On the provided JSON, we have two test cases: "FillRect" and "PutImageData". These test cases are designed to measure the performance of filling pixels on an HTML canvas element using JavaScript.
In general, these tests aim to compare the speed of two different approaches:
fillRect
method directly on the canvas context to fill each pixel individually.createImageData
method to create an image data object, populates it with the pixel values, and then applies this image data to the canvas using the putImageData
method.Options being compared
The two approaches have different pros and cons:
fillRect
and possibly causing browser rendering pauses.putImageData
, which can be optimized by the browser's renderer. Additionally, this method avoids repeated calls to fillRect
.Library usage
In both test cases, we see that JavaScript's built-in canvas API (document.getElementById('c').getContext('2d')
) is used to interact with the canvas element. The createImageData
method is part of this API, which allows us to create an image data object from a specified width and height.
Special JS features or syntax
There are no specific JavaScript features or syntax mentioned in the provided code that would be unique to these test cases. However, it's worth noting that using canvas elements with JavaScript is a fundamental part of creating interactive graphics and animations on the web.
Other alternatives
If you're looking for alternative ways to fill pixels on an HTML canvas element, here are some options:
createImageData
and putImageData
.canvas-pixel-manipulation
, that provide functions for manually manipulating individual pixels on the canvas element.Keep in mind that these alternatives might have different trade-offs and requirements compared to the built-in createImageData
and putImageData
methods.