R
R
Ragtime Kitty2019-04-15 13:53:01
JavaScript
Ragtime Kitty, 2019-04-15 13:53:01

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);

The font has to be set twice, because if you remove it before setting the width, then measureText will be calculated using the default font. If you remove after, then the text itself will be drawn with the default font. I tried to save the context before setting the width and restore after, but to no avail.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-04-15
@Ragtime_Kitty

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 question

Ask a Question

731 491 924 answers to any question