admin管理员组

文章数量:1333193

I am rendering text onto a HTML-Canvas like so:

.asp?filename=FMSIQUFFO5PL

As you can see, the text is supposed to be rendered at 32, 32. But for some reasons, the string appears too high.

It this because the Canvas' coordinates start at the top left corner of the Canvas-Element and the String's coordinates at the lower left corner of the String?

How do I work around this issue so that I can render text at exactly the position I am expecting it to be?

I am rendering text onto a HTML-Canvas like so:

https://www.w3schools./code/tryit.asp?filename=FMSIQUFFO5PL

As you can see, the text is supposed to be rendered at 32, 32. But for some reasons, the string appears too high.

It this because the Canvas' coordinates start at the top left corner of the Canvas-Element and the String's coordinates at the lower left corner of the String?

How do I work around this issue so that I can render text at exactly the position I am expecting it to be?

Share Improve this question asked Dec 24, 2017 at 20:36 MarkallMarkall 1737 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

By default the vertical text-alignment (baseline) is set to "alphabetic" which uses the general bottom of the text for the y coordinate.

You can change this behavior by setting textBaseline to "top".

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "32px Arial";
ctx.textAlign = "left";
ctx.textBaseline = "top";   // change baseline property
ctx.fillText("Hello World", 32, 32);
<canvas id="myCanvas" style="border:1px solid #d3d3d3;"></canvas>

本文标签: javascriptWhy does the CanvasFillText method seem to use the wrong coordinatesStack Overflow