使用 HTML5 的画布绘制带有外部笔划的文本 [英] Drawing text with an outer stroke with HTML5's canvas

查看:18
本文介绍了使用 HTML5 的画布绘制带有外部笔划的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 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))

这篇关于使用 HTML5 的画布绘制带有外部笔划的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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