To set Letter spacing in canvas element with JavaScript, we can set the canvas element’s style.letterSpacing
property.
For instance, we can write:
<canvas style='width: 300px; height: 300px'></canvas>
to add the canvas element.
Then, we write:
const can = document.querySelector('canvas');
const ctx = can.getContext('2d');
can.width = can.offsetWidth;
ctx.clearRect(0, 0, can.width, can.height);
can.style.letterSpacing = '10px'
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '4em sans-serif';
ctx.fillText('Hello', can.width / 2, can.height * 1 / 4);
can.style.letterSpacing = '30px'
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '4em sans-serif';
ctx.fillText('World', can.width / 2, can.height * 3 / 4);
to get the canvas with document.querySelector
.
Then we get the canvas context with getContext
.
Next, we set the can.style.letterSpacing
to set the letter spacing we want for our text.
We also, set the textAlign
, textBaseline
, and font
properties to set the font style we want.
Finally, we call fillText
to draw the text onto the canvas.
The arguments are the text, width, and height of the text respectively.