As a frontend starter, I've just started to learn canvas. I'm trying to draw some text. But the size of canvas could not display correctly at once: My code for creating canvas:
const message = input.value;
let ctx = canvas.getContext('2d')
let metrics = ctx.measureText(message);
let textWidth = metrics.width*2;
canvas.width = textWidth;
canvas.height = 200;
ctx.font = "normal 30px Verdana";
ctx.fillStyle = "#000000";
ctx.fillText(message, 30, 200);
<input id=input value="init message" />
<canvas id=canvas></canvas>
and the result is:enter image description here
as you can see, the message can't be fully displayed, but when I click the button to run function draw() again, then the canvas can be fully displayed:
enter image description here
Could anyone please tell me why this happens.