I want to have a text at the very bottom of the canvas, so I do:
ctx.textAlign = 'center';
ctx.fillText(text, canvas.width / 2, canvas.width);
That works nice for every type of char but square brackets are cut off at the bottom:
Large text:
Small text:
One solution would be to just set the y value to canvas.width - someSpacing
but there is a different count of pixels cutoff at the small and big text.
So is there a way that the brackets aren't cut off?
var canvas = document.getElementById("mycanvas");
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext('2d');
ctx.font = "30px Arial";
ctx.textAlign = "right";
ctx.fillText("[027722]", canvas.width, canvas.width)
ctx.font = "11px Arial";
ctx.textAlign = "left";
ctx.fillText("[027722]", 10, canvas.width)
<canvas id="mycanvas"></canvas>
This has to do with the baseline of fonts. In Typography this term is used to describe an imaginary ground where the text actually 'rests'. The canvas API offers six different types of baselines.
As you might assume from the above, canvas defaults to 'alphabetic'.
Luckily the fix is simple - you just need to switch the baseline to either bottom or ideographic. This can be done by changing the .textBaseline
property accordingly.
let canvas = document.getElementById("myCanvas");
canvas.width = 200;
canvas.height = 200;
let ctx = canvas.getContext('2d');
ctx.textBaseline = "bottom";
ctx.font = "30px Arial";
ctx.textAlign = "right";
ctx.fillText("[027722]", canvas.width, canvas.height)
ctx.font = "11px Arial";
ctx.textAlign = "left";
ctx.fillText("[027722]", 10, canvas.height)
<canvas id="myCanvas" style="background: #f9f9f9">