[英]How do I style HTML5 canvas text to be bold and/or italic?
I'm printing text to a canvas in a pretty straight forward way:我以非常直接的方式将文本打印到 canvas:
var ctx = canvas.getContext('2d');
ctx.font = "10pt Courier";
ctx.fillText("Hello World", 100, 100);
But how can I change the text to bold, italic or both?但是如何将文本更改为粗体、斜体或两者兼而有之? Any suggestions to fix that simple example?有什么建议可以解决这个简单的例子吗?
You can use any of these:您可以使用以下任何一种:
ctx.font = "italic 10pt Courier";
ctx.font = "bold 10pt Courier";
ctx.font = "italic bold 10pt Courier";
For further information, here are a couple of resources:欲了解更多信息,这里有一些资源:
Just an additional heads up for anyone who stumbles across this: be sure to follow the order shown in the accepted answer.对于偶然发现此问题的任何人,请额外提醒一下:请务必遵循已接受答案中显示的顺序。
I ran into some cross-browser issues when I had the wrong order.当我有错误的订单时,我遇到了一些跨浏览器的问题。 Having "10px Verdana bold" works in Chrome, but not in IE or Firefox. “10px Verdana bold”在 Chrome 中有效,但在 IE 或 Firefox 中无效。 Switching it to "bold 10px Verdana" as indicated fixed those problems.按照指示将其切换为“bold 10px Verdana”可以解决这些问题。 Double-check the order if you run into similar problems.如果遇到类似问题,请仔细检查订单。
Underline is not possible through any of the canvas methods or properties.无法通过任何画布方法或属性添加下划线。 But I did some work around to get it done.但我做了一些工作来完成它。 You can check it out @ http://scriptstock.wordpress.com/2012/06/12/html5-canvas-text-underline-workaround您可以查看@ http://scriptstock.wordpress.com/2012/06/12/html5-canvas-text-underline-workaround
You can find the implementation here http://jsfiddle.net/durgesh0000/KabZG/你可以在这里找到实现http://jsfiddle.net/durgesh0000/KabZG/
So there's no way to just set font-weight
(or font-size
or font-family
...) in one JS command?所以没有办法只在一个 JS 命令中设置font-weight
(或font-size
或font-family
......)? It all has to be in one complete font string?这一切都必须在一个完整的字体字符串中吗?
If you need to allow for variations in formatting, you can set a font style, draw text, measure it using measureText
, set a new style, and then draw the next block like this:如果您需要允许格式的变化,您可以设置字体样式、绘制文本、使用measureText
对其进行measureText
、设置新样式,然后像这样绘制下一个块:
// get canvas / context var can = document.getElementById('my-canvas'); var ctx = can.getContext('2d') // draw first text var text = '99%'; ctx.font = 'bold 12pt Courier'; ctx.fillText(text, 50, 50); // measure text var textWidth = ctx.measureText(text).width; // draw second text ctx.font = 'normal 12pt Courier'; ctx.fillText(' invisible', 50 + textWidth, 50);
<canvas id="my-canvas" width="250" height="150"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.