Reputation: 81
I am working on a canvas based app, and I have some problems with the vertical alignment of my texts. I am using floating point coordinates, which I think are the cause of the problem. I am not sure though, and am nonetheless looking for a solution. Anyway, the code I use for displaying the letter 'O' in a square, for instance, is:
context.fillRect(0, 0, 21.864951768488744, 21.864951768488744);
context.textBaseline = 'middle';
context.textAlign = alignLeft ? 'left' : 'center';
context.fillText('O', 10.932475884244372, 10.932475884244372);
The result on the canvas is that the 'O' is centered horizontally, but placed about 1 - 2 pixels above the center.
Does anyone have any thoughts on this?
Upvotes: 7
Views: 19823
Reputation: 810
It's leaving space for characters with descenders. Add something with a descender like a "y" to see what I mean.
var c = document.getElementById("myCanvas");
var context= c.getContext("2d");
context.fillStyle = "#FF0000";
context.fillRect(0, 0, 21.864951768488744, 21.864951768488744);
context.font = "10px Arial";
context.fillStyle = "#FFffff";
context.textBaseline = 'middle';
context.textAlign = 'center';
context.fillText('Oy', 10.932475884244372, 10.932475884244372);
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
Upvotes: 11
Reputation: 81
It seems that there indeed is a problem with floating coordinates when writing texts. As the example - http://codepen.io/petor/pen/NRPgVq - clearly shows texts cannot be displayed on subpixel coordinates and will be placed on rounded coordinates (at least on Chrome).
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var context= c.getContext("2d");;
context.font = "10px Arial";
context.fillText('O', 0, 10);
context.fillText('O', 10, 10.1);
context.fillText('O', 20, 10.2);
context.fillText('O', 30, 10.3);
context.fillText('O', 40, 10.4);
context.fillText('O', 50, 10.5);
context.fillText('O', 60, 10.6);
context.fillText('O', 70, 10.7);
context.fillText('O', 80, 10.8);
context.fillText('O', 90, 10.9);
context.fillText('O', 100, 11);
</script>
</body>
</html>
Upvotes: 1