Canvas Measure Text

Benchmark created by Yi on


Preparation HTML

<canvas id='canvas'/>

Setup

const texts = [];
  		const maxLen = 50;
  		const size = 4000;
  
  		for (let i=0; i<size; ++i) {
  			const len = Math.floor(Math.random() * maxLen);
  			let text = "";
  			for(let j=0; j<len; ++j) {
  				const char = String.fromCharCode(65 + Math.floor(Math.random() * 58));
  				text += char;
  			}
  			texts.push(text);
  		}
  
  canvasCtx = document.getElementById('canvas').getContext('2d');
  canvasCtx.font = '10px sans-serif';
  i = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
Test with different length of texts
var width = canvasCtx.measureText(texts[i % size]).width;
//console.log('canvas: ' + width);
i++;
ready
Same test
var width = canvasCtx.measureText(texts[i % size]).width;
//console.log('canvas: ' + width);
i++;
ready

Revisions

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