canvas: batch draws

Benchmark created on


Preparation HTML

<canvas id="canvas" />

Setup

const canvas = document.getElementById('canvas');

const ctx = canvas.getContext('2d');
canvas.width = 100;
canvas.height = 100;

const points = [];
for (let x = 0; x < 100; x++) {
	for (let y = 0; y < 100; y++) {
		points.push({x, y})
	}
}

const tenPoints = points.slice(0, 10);

// for prerendering
const offscreenCanvas = new OffscreenCanvas(100, 100);
const offctx = offscreenCanvas.getContext('2d');
offctx.beginPath();
for (let i = 0; i < points.length - 1; i++) {
  const p1 = points[i];
  const p2 = points[i+1];
  offctx.moveTo(p1.x, p1.y);
  offctx.lineTo(p2.x, p2.y);
}
offctx.stroke();
const prerenderedImage = offscreenCanvas.transferToImageBitmap();

const offscreenCanvas2 = new OffscreenCanvas(1, 1);
const offctx2 = offscreenCanvas2.getContext('2d');
offctx2.beginPath();
offctx2.moveTo(0, 0);
offctx2.lineTo(1, 0);
offctx2.stroke();
const prerenderedSegment = offscreenCanvas2.transferToImageBitmap();

Test runner

Ready to run.

Testing in
TestOps/sec
Segmented line draws
for (let i = 0; i < points.length - 1; i++) {
  const p1 = points[i];
  const p2 = points[i+1];
  ctx.beginPath();
  ctx.moveTo(p1.x, p1.y);
  ctx.lineTo(p2.x, p2.y);
  ctx.stroke();
}
ready
Single line draw
ctx.beginPath();
for (let i = 0; i < points.length - 1; i++) {
  const p1 = points[i];
  const p2 = points[i+1];
  ctx.moveTo(p1.x, p1.y);
  ctx.lineTo(p2.x, p2.y);
}
ctx.stroke();
ready
Smaller amount of lines (segmented draw)
for (let i = 0; i < tenPoints.length - 1; i++) {
  const p1 = tenPoints[i];
  const p2 = tenPoints[i+1];
  ctx.beginPath();
  ctx.moveTo(p1.x, p1.y);
  ctx.lineTo(p2.x, p2.y);
  ctx.stroke();
}
ready
Smaller amount of lines (single draw)
ctx.beginPath();
for (let i = 0; i < tenPoints.length - 1; i++) {
  const p1 = tenPoints[i];
  const p2 = tenPoints[i+1];
  ctx.moveTo(p1.x, p1.y);
  ctx.lineTo(p2.x, p2.y);
}
ctx.stroke();
ready
Prerendered full image draw
ctx.drawImage(prerenderedImage, 0, 0);
ready
Prerendered segmented draws
for (let i = 0; i < points.length - 1; i++) {
  const p = points[i];
  ctx.drawImage(prerenderedSegment, p.x, p.y);
}
ready

Revisions

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