Make text pattern background with <canvas>

I’m writing a new article and actually this is a part of it. I’ll describe a method that I used to generate textures in Three.js.

But I decided to describe some methods as separate articles to be more flexible and don’t worry about the amount of text and structuring.

What we will do

We will make text → repeat it on canvas → convert it to image → add the image as a background.

I will do it with React, but it doesn't matter because we will write a function that you can use with plain JS as well.

Here are two methods:

1. Generate text and adjust canvas size to the text width

2. And the second method adjust the text to the canvas width

Both of them are almost the same, except for a few lines. But in my work, I will use the first version + for me the first version is better because we have control under the canvas width.

Let`s call our function generateTexture()

Set variables

Let’s set variables that we could use more than once or that we could provide as changeable properties in the future.

bitmapShift will shift the pattern down. We need it to check that the texture looks seamless.

copyamount it's the number of text lines in the tile.

canvasSize is the size of the canvas and the size of the texture that we will use as a background image.

fontSize will calculate the text size based on how much rows we want to add to the tile.

Then we create our canvas and set the size.

Add fill style (text color) and style.

To measure text we use measureText method. And then scale the text X size based on he textWidth variable.

Also, we add a function that duplicates each new text clone one below another.

Clone text but add +1 to the amount to be able to offset text position properly, because 1 * 0 = 0

Finally, we convert canvas to the image data and now can return the result and use it as a background image.

Nerd and visual maniac