If you’ve looked at HTML5’s canvas tag at all, then you’ve probably heard people mention prerendering elements on another canvas to speed up your code. The main reason to do this is the eliminate the need to draw the same thing over and over when you can just draw it once. Drawing text with a stroke on the canvas is a perfect example of this.
Say you have some code like this:
1 2 3 4 5 6 7 8 | ctx.fillStyle = '#0f0'; ctx.font = 'bold 60px Arial'; ctx.textBaseline = 'top'; ctx.fillText('Hello World', 0, 0); ctx.strokeStyle = '#000'; ctx.lineWidth = 3; ctx.font = 'bold 60px Arial'; ctx.strokeText('Hello World', 0, 0); |
We have some text that says “Hello World” and then we put a three pixel stroke around it. This is pretty basic stuff but think about it this way. Say this text is in a game that’s running at sixty frames a second, the browser is going to have to draw that text and the stroke over and over. And some platforms, like the iPad, slow down tremendously when you add a stroke. We could just swap out the text for an image which would be faster, but then we wouldn’t be able to make the text dynamic.
Another option is to create a canvas tag, draw our text on it once and then render that text on the other canvas like an image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | var canvas = document.querySelector('#canvas'); var ctx = canvas.getContext('2d'); var textCanvas = document.createElement('canvas'); var textCtx = textCanvas.getContext('2d'); textCanvas.width = 400; textCanvas.height = 100; textCtx.fillStyle = '#0f0'; textCtx.font = 'bold 60px Arial'; textCtx.textBaseline = 'top'; textCtx.fillText('Hello World', 0, 0); textCtx.strokeStyle = '#000'; textCtx.lineWidth = 3; textCtx.font = 'bold 60px Arial'; textCtx.strokeText('Hello World', 0, 0); function draw() { ctx.clearRect(0,0,canvas.width,canvas.height); ctx.drawImage(textCanvas, 10, 10); setTimeout(draw, 1000/60); } draw(); |
This is a pretty simple example but I think it shows what you could do in a more complex program. If you’re building a game and have a bunch of elements moving around on the canvas, the last thing you want is some text with a stroke stealing your processing power.