Canvas getImageData/setImageData vs drawRect()

Benchmark created on


Description

For pixel based drawing, this checks which one is faster, [get|set]ImageData or drawRect()

Preparation HTML

<canvas id="drawRect" ></canvas>
<canvas id="imageData" ></canvas>

Setup

const drawRectCanvas = document.getElementById("drawRect");
const imageDataCanvas = document.getElementById("imageData");


drawRectCanvas.height = 100;
drawRectCanvas.width = 100;
drawRectCanvas.style.height = "100px";
drawRectCanvas.style.width = "100px";
imageDataCanvas.height = 100;
imageDataCanvas.width = 100;

imageDataCanvas.style.height = "100px";
imageDataCanvas.style.width = "100px";


const imageDataCanvasCtx = imageDataCanvas.getContext("2d");
const drawRectCanvasCtx = drawRect.getContext("2d")

imageDataCanvasCtx.clearRect(0,0,100,100)
drawRectCanvasCtx.clearRect(0,0,100,100)

const imageData = imageDataCanvasCtx.createImageData(100,100);

Test runner

Ready to run.

Testing in
TestOps/sec
Get/SetImageData
for(let i =0;i<imageData.data.length;i+=4){
	imageData.data[i] = Math.floor(Math.random()*255);
	imageData.data[i+1] = Math.floor(Math.random()*255);
	imageData.data[i+2] = Math.floor(Math.random()*255);
  
	imageData.data[i+3] = 255;
}
ready
Draw Rect
for(let i=0;i<100*100;++i){
	const x = i%100;
  const y = Math.floor(i/100);
  	
  const randomColor = Math.floor(Math.random()*0xffffff).toString(16).padStart(6,"0")
  drawRectCanvasCtx.fillStyle = `#${randomColor}`;
  drawRectCanvasCtx.fillRect(x,y,1,1);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.