使用 HTML5 的画布绘制带有外部笔划的文本

2022-01-17 00:00:00 canvas javascript html html5-canvas

我目前正在使用 HTML5 的画布使用 fillText 方法来呈现多个字符串.这很好用,但我也想给每个字符串一个 1px 黑色外笔划.不幸的是,strokeText 函数似乎应用了内部笔划.为了解决这个问题,我编写了一个 drawStrokedText 函数来实现我想要的效果.不幸的是,它太慢了(原因很明显).

I'm currently using HTML5's canvas to render a number of strings using the fillText method. This works fine, but I'd also like to give each string a 1px black outer stroke. Unfortunately the strokeText function seems to apply an inner stroke. To counter this, I've written a drawStrokedText function that achieves the effect I'm after. Unfortunately it's horrible slow (for obvious reasons).

有没有一种快速、跨浏览器的方法可以使用原生画布功能实现 1 像素的外部笔划?

Is there a fast, cross-browser way of achieving a 1px outer stroke using native canvas functionality?

drawStrokedText = function(context, text, x, y)
{
    context.fillStyle = "rgb(0,0,0)";
    context.fillText(text, x-1, y-1);
    context.fillText(text, x+1, y-1);
    context.fillText(text, x-1, y);
    context.fillText(text, x+1, y);
    context.fillText(text, x-1, y+1);
    context.fillText(text, x+1, y+1);

    context.fillStyle = "rgb(255,255,255)";
    context.fillText(text, x, y);
};

这是一个工作效果的例子:

Here's an example of the effect at work:

推荐答案

中风是怎么回事?由于一半的笔画将在形状之外,因此您始终可以先绘制笔画,线宽为您想要的两倍.所以如果你想要一个 4px 的外笔画,你可以这样做:

What's wrong with stroke? Since half the stroke will be outside of the shape, you can always draw the stroke first with a line width of double what you want. So if you wanted a 4px outer stroke you could do:

function drawStroked(text, x, y) {
    ctx.font = '80px Sans-serif';
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 8;
    ctx.strokeText(text, x, y);
    ctx.fillStyle = 'white';
    ctx.fillText(text, x, y);
}


drawStroked("37°", 50, 150);

这使得:

现场小提琴:http://jsfiddle.net/vNWn6/

如果碰巧在较小的文本渲染比例下看起来不太准确,您始终可以将其绘制得较大但按比例缩小(在上述情况下,您会执行 ctx.scale(0.25, 0.25))

IF that happens to not look as accurate at smaller text rendering scales, you can always draw it large but scale it down (in the above case you'd do ctx.scale(0.25, 0.25))

相关文章