Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing text with an outer stroke with HTML5's canvas

Tags:

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:

enter image description here

like image 803
ndg Avatar asked Nov 29 '12 13:11

ndg


People also ask

Which method is used to draws text on the canvas?

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)

Can a canvas contain text?

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.

How do I add a shadow to text in canvas?

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.


1 Answers

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:

enter image description here

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

like image 186
Simon Sarris Avatar answered Sep 21 '22 07:09

Simon Sarris