Answer the question
In order to leave comments, you need to log in
Canvas: how to set font and then resize?
Hello.
I want to draw text on a canvas and set its width to the same size as the text.
var
canvas = document.querySelector('canvas'),
ctx = canvas.getContext("2d"),
text = "Apples"
ctx.font = "small-caps 44px Arial";
canvas.width = ctx.measureText(text).width;
ctx.font = "small-caps 44px Arial";
ctx.textBaseline = 'middle';
ctx.fillText(text, 0, canvas.height / 2);
Answer the question
In order to leave comments, you need to log in
It seems that by changing canvas.width the canvas parameters are reset to default, which in my opinion is a logical behavior. If so, then you need to either look for a solution with a once-specified, fixed width of the canvas, or do as you did (set the font 2 times)
PS: as I said, changing the size of the canvas resets some of its parameters to default
https://www. w3.org/html/wg/spec/the-canvas-element.html
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question