Letter spacing in canvas element

前端 未结 10 2354
攒了一身酷
攒了一身酷 2020-12-24 06:46

The question says it all pretty much. I\'ve been searching around and starting to worry that it\'s impossible.

I\'ve got this canvas element that I\'m drawing text t

10条回答
  •  天命终不由人
    2020-12-24 07:11

    You can't set the letter spacing property, but you you can accomplish wider letter spacing in canvas by inserting one of the various white spaces in between every letter in the string. For instance

    ctx.font = "3em sheepsans";
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    ctx.fillStyle = "rgb(255, 255, 255)";
    var ctext = "Blah blah text".split("").join(String.fromCharCode(8202))
    ctx.fillText(ctext, 1024 / 2, 768 / 2);
    

    This will insert a hair space between every letter.

    Using 8201 (instead of 8202) will insert the slightly wider thin space

    For more white space options, see this list of Unicode Spaces

    This method will help you to preserve the font's kerning much more easily than manually positioning each letter, however you wont be able to tighten your letter spacing this way.

提交回复
热议问题