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).
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:
To draw text on a canvas, the most important property and methods are: font - defines the font properties for the text. fillText(text,x,y) - draws "filled" text on the canvas. strokeText(text,x,y) - draws text on the canvas (no fill)
The canvas rendering context provides two methods to render text: fillText(text, x, y [, maxWidth]) Fills a given text at the given (x,y) position. Optionally with a maximum width to draw.
To add shadow to text, use the shadowOffsetX and shadowOffsetY attributes. shadowOffsetX = number of pixels offset in the x direction; shadowOffsetY = number of pixels offset in the y direction; A blur effect added to the shadows will make the text beveled.
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);
Which makes:
live fiddle here: http://jsfiddle.net/vNWn6/
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With