Drawing text with an outer stroke with HTML5#39;s canvas(使用 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 的画布绘制带有外部笔划的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 HTML5 的画布绘制带有外部笔划的文本
基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
