AMORE
AMORE

Reputation: 109

canvas' size could not display correctly at once

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.

Upvotes: 3

Views: 79

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17594

There are a couple of thing you need to do:

  • call measureText after you set the font or the width will be incorrect
  • after changing a canvas dimensions you need to reset the font

On your code you will need to set the font twice.
First before we measure, Second after we change the canvas width and height; I added a console.log to my sample you can see that after canvas change dimensions the font changes to default; Here is a working sample:

const message = "Hello World"
const font = "normal 30px Verdana"

let canvas = document.getElementById("c");
let ctx = canvas.getContext('2d');

ctx.font = font;
let metrics = ctx.measureText(message);
canvas.width = metrics.width * 2;
canvas.height = 100;
console.log(ctx.font)

ctx.font = font;
ctx.fillText(message, 30, 90);
canvas {
  border: 2px solid #0000AA
}
<canvas id="c"></canvas>

Upvotes: 2

Related Questions