Is it possible to draw text (underline, etc.) using the HTML5 Canvas Text API?

I am using the HTML5 canvas API to display some string (canvas.fillText), and I was wondering if text decoration (e.g. underline, strikethrough, etc.) is possible using the api canvas. Unfortunately, I did not find anything about this. The only solution I found was to manually make the decoration using api canvas painting (I mean by explicitly drawing a horizontal line, for example, to simulate the "underline" decoration). Is this possible using api canvas text?

Thanks Patrick

+11
html5 canvas
Jan 07 '11 at 15:30
source share
3 answers

It will not work with the built-in method, but there is a simplified function here that I have successfully used based on its reading. http://scriptstock.wordpress.com/2012/06/12/html5-canvas-text-underline-workaround/

var underline = function(ctx, text, x, y, size, color, thickness ,offset){ var width = ctx.measureText(text).width; switch(ctx.textAlign){ case "center": x -= (width/2); break; case "right": x -= width; break; } y += size+offset; ctx.beginPath(); ctx.strokeStyle = color; ctx.lineWidth = thickness; ctx.moveTo(x,y); ctx.lineTo(x+width,y); ctx.stroke(); } 
+7
Jan 23 '13 at 17:36
source share

I'm sorry to say no. There are no text decorations or similar styles in the text methods of the HTML Canvas context.

+1
Jan 07 '11 at 17:31
source share

Patrick, you can do this easily using fillRect as follows:

 ctx.fillText("Hello World", 0, 0); var text = ctx.measureText("Hello World"); ctx.fillRect(xPos, yPos, text.width, 2); 

The only difficult part of this approach is that there is no way to get a measurement of height use. Otherwise, you can use this as your Y coordinate when drawing a fillRect.

Your Y position will depend only on the height of your text and on how close you want to emphasize.

0
Jun 05 '15 at 19:32
source share



All Articles