本文介绍了使用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).

有一种快速的跨浏览器方式使用本地画布功能实现1px外部笔画?

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);

这样做:

live fiddle here:

live fiddle here: 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的画布绘制带外笔画的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 13:33