<canvas id="canvas" width="320" height="320"></canvas>
const canvas = document.getElementById('canvas')
canvas.style.imageRendering = 'pixelated'
canvas.style.backgroundColor = '#000'
canvas.style.outline = 'none'
canvas.style.cursor = 'none'
canvas.style.transform = `scale(2)`
document.body.replaceChildren(canvas)
const ctx = canvas.getContext('2d')
function drawimgdata(img) {
ctx.drawImage(img, 0, 0)
img.close()
}
function drawpixels(pixels) {
const imgdata = new ImageData(pixels, 320, 180)
ctx.putImageData(imgdata, 0, 0)
}
function drawrandom() {
// for (let n = 0; n < 300; n++)
for (let y = 0; y < 180; y++) {
for (let x = 0; x < 320; x++) {
let i = y * 320 * 4 + x * 4
pixels[i + 0] = Math.random() * 255
pixels[i + 1] = Math.random() * 255
pixels[i + 2] = Math.random() * 255
pixels[i + 3] = 255
}
}
}
const c = new OffscreenCanvas(320, 180)
const ctx2 = c.getContext('2d')
const pixels = new Uint8ClampedArray(320 * 180 * 4)
const imgdata = new ImageData(pixels, 320, 180)
drawrandom()
ctx2.putImageData(imgdata, 0, 0)
drawimgdata(c.transferToImageBitmap())
drawrandom()
drawpixels(pixels)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
imgdata | |
pixels |
Test name | Executions per second |
---|---|
imgdata | 1130.2 Ops/sec |
pixels | 1163.8 Ops/sec |
This benchmark compares two different methods of rendering images to a canvas in a web browser using JavaScript’s Canvas API. The specific methods being tested are putImageData
and drawImage
, which are commonly used for manipulating image data on HTML canvas elements.
putImageData vs drawImage manual
imgdata
): Uses drawImage
in combination with ImageBitmap
via transferToImageBitmap()
.pixels
): Uses putImageData
to draw directly from a pixel array (Uint8ClampedArray
).drawImage
with transferToImageBitmap()
:
ImageBitmap
using the transferToImageBitmap()
method.drawImage
method draws the ImageBitmap
to the main canvas.ImageBitmap
is designed for efficient memory use in graphics-heavy applications.ImageBitmap
effectively.putImageData
:
putImageData
.putImageData
processes pixel data one pixel at a time and can be performance intensive.From the test results, we observe:
pixels
method (with putImageData
): 1163.84 executions/secondimgdata
method (with drawImage
): 1130.18 executions/secondThe pixels
method outperforms the imgdata
method slightly, indicating that for this specific benchmark, using putImageData
may be more efficient under the conditions tested.
In addition to putImageData
and drawImage
, other potential alternatives for rendering images on canvas include:
The benchmark provides valuable insights into performance differences between two commonly used rendering methods in JavaScript. While putImageData
has shown better performance in this test scenario, the choice of which method to use will depend on the specific requirements of the application, including factors like complexity, browser compatibility, and rendering performance needed.