I am using the HTML5
canvas API to display some string (canvas.fillText), and I was wondering whether text-decoration (like underline, strikethrough, etc.) was something possible with the canvas API. Unfortunately, I found nothing about this.
The only solution I found was to manually do the decoration using the canvas drawing API (I mean, explicitly drawing a horizontal line, for example, to mimic the 'underline' decoration).
Is this possible using the canvas text API?
UPDATE: You can now easily underline text in Canva just as you'd expect to be able to to! Simply select your text, and then go to the “U” symbol in the text options.
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 <u> tag in HTML stands for underline, and it's used to underline the text enclosed within the <u> tag. This tag is generally used to underline misspelled words. This tag requires a starting as well as ending tag.
Solution with Javascript To add a text to the HTML <canvas> element, you need to use the fillText() or strokeText() methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.
It won't work with a built-in method, but here is a simplified function I used successfully based on reading, "HTML5 Canvas: Text underline workaround" on the ScriptStock website.
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();
}
You can do this by using measureText
and fillRect
like so:
ctx.fillText(text, xPos, yPos);
let { width } = ctx.measureText("Hello World");
ctx.fillRect(xPos, yPos, width, 2);
The only difficult part about this approach is there is no way to obtain the height use measureText. Otherwise, you could use that as your Y coordinate when drawing your fillRect.
Your Y position will only depend on the height of your text and how close you'd like the underline.
// get canvas / context
var can = document.getElementById('my-canvas');
var ctx = can.getContext('2d')
let xPos=10, yPos=15;
let text = "Hello World"
ctx.fillText(text, xPos, yPos);
let { width } = ctx.measureText("Hello World");
ctx.fillRect(xPos, yPos, width, 2);
<canvas id="my-canvas" width="250" height="150"></canvas>
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