画布元素中的字母间距 [英] Letter spacing in canvas element

查看:212
本文介绍了画布元素中的字母间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题说的很多。我一直在寻找,开始担心这是不可能的。

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

我有这个画布元素,我正在绘制文本。我想设置字母间距类似于CSS letter-spacing 属性。

I've got this canvas element that I'm drawing text to. I want to set the letter spacing similar to the CSS letter-spacing attribute. By that I mean increasing the amount of pixels between letters when a string is drawn.

我的代码绘制文本是这样,ctx是画布上下文变量。

My code for drawing the text is like so, ctx is the canvas context variable.

ctx.font = "3em sheepsans";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fillText("Blah blah text", 1024 / 2, 768 / 2);

我试过添加 ctx.letterSpacing =2px code>在绘图前,但没有效果。有一种方法可以做一个简单的设置,或者我必须制作一个函数,以单独绘制每个字符间距的思想?

I've tried adding ctx.letterSpacing = "2px"; before the drawing but with no avail. Is there a way to do this just with a simple setting, or will I have to make a function to individually draw each character with the spacing in mind?

推荐答案

这是不可能的; HTML5 Canvas没有HTML中所有CSS的文本转换功能。我建议你应该结合适当的技术为每种用法。

This is not possible; the HTML5 Canvas does not have all the text-transformation power of CSS in HTML. I would suggest that you should combine the appropriate technologies for each usage. Use HTML layered with Canvas and perhaps even SVG, each doing what it does best.

请注意,滚动自己 - 使用自定义偏移量绘制每个字符 - 会对大多数字体产生不良结果,因为有字母间距对和像素对齐字体提示。

Note also that 'rolling your own'—drawing each character with a custom offset—is going to produce bad results for most fonts, given that there are letter kerning pairs and pixel-aligned font hinting.

这篇关于画布元素中的字母间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆