如何将 HTML5画布文本设置为粗体和/或斜体?

我以一种非常直接的方式将文本打印到画布上:

var ctx = canvas.getContext('2d');
ctx.font = "10pt Courier";
ctx.fillText("Hello World", 100, 100);

但是我怎样才能把文本改成粗体、斜体或者两者兼而有之呢? 有什么建议来修改这个简单的例子吗?

95701 次浏览

From the MDN documentation on CanvasRenderingContext2D.font:

The CanvasRenderingContext2D.font property of the Canvas 2D API specifies the current text style to use when drawing text. This string uses the same syntax as the CSS font specifier.

So, that means any of the following will work:

ctx.font = "italic 10pt Courier";


ctx.font = "bold 10pt Courier";


ctx.font = "italic bold 10pt Courier";

Here are a couple of additional resources for more information:

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

You can find the implementation here http://jsfiddle.net/durgesh0000/KabZG/

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. Switching it to "bold 10px Verdana" as indicated fixed those problems. Double-check the order if you run into similar problems.

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:

// 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>

Further Reading