几年前,我为 APNGedit 制作了一个 Javascript 脚本来绘制 Laughing Man 标志。它使用了现已失效的mozTextAlongPath
我最近重新发现了这个脚本,并使用翻译、旋转和 fillText() 重新编写了它。但是,这不尊重字符宽度,也没有紧缩(看起来很糟糕)。
大约 2009 年的原版(不完美,但还可以):
当前版本:
如何在 HTML5 画布上以弧形绘制文本并使其看起来不错?
基于 Kolink 答案的解决方案代码:
ctx.fillStyle = primaryColor;
ctx.font = fontSize + 'px ' + fontFamily;
var textWidth = ctx.measureText(text).width,
charRotation = 0,
character, charWidth, nextChar, nextWidth, bothWidth, kern, extraRotation, charSegment;
for (var i=0, l=text.length; i<l; i++) {
character = nextChar || text[i];
charWidth = nextWidth || ctx.measureText(character).width;
// Rotate so the letter base makes a circle segment instead of a tangent
extraRotation = (Math.PI/2) - Math.acos((charWidth/2) / radius);
ctx.save();
ctx.translate(radius, h/2);
ctx.rotate(charRotation);
ctx.translate(0, -textRadius);
ctx.rotate(extraRotation);
ctx.fillText(character,0,0);
ctx.restore();
nextChar = text[i+1] || '';
nextWidth = ctx.measureText(nextChar).width;
bothWidth = ctx.measureText(character+nextChar).width;
kern = bothWidth - charWidth - nextWidth;
charSegment = (charWidth+kern) / textWidth; // percent of total text size this takes up
charRotation += charSegment * (Math.PI*2);
}