Reputation: 1580
I'm trying to draw a line under a string of characters on an HTML Canvas and the value coming back from measureText is wrong.
Here's the code:
var theCanvas = document.querySelector('canvas')
var ctx = theCanvas.getContext("2d");
if (ctx) {
var theString = "Drawing Text on a Canvas";
ctx.font = "28px Verdana"
ctx.fillText(theString, 20, 160);
var textW = ctx.measureText(theString);
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.moveTo(20, 170);
ctx.lineTo(Math.round(textW.width), 170);
ctx.stroke();
}
<canvas width="600" height="200"></canvas>
The line doesn't reach all the way to the end of the string.
Upvotes: 2
Views: 911
Reputation: 1114
When you set the endpoint of the line, you're forgetting to take the offset into account. Your text starts at x = 20, then it should end at the calculated endpoint + 20
Instead of (x,y) = Math.round(textW.width), 170
, then it should be (x,y) = Math.round(textW.width) + 20, 170
Upvotes: 2