Valuator
Valuator

Reputation: 3617

Positioning text in HTML5 canvas

I'm trying to place text inside of a canvas element. In this example, I want to put 48px high text inside of a 64px high canvas. The text should therefore take up 3/4 of the height of the canvas. However, in everything I've tried, the text only occupies the upper part of the canvas and get squished into that space the larger I make it.

If I start at 0, 0; nothing appears in the canvas, so I moved to 0, 64 to start. This places the text inside but the scaling is off as mentioned before. If I go all the way to 0, 128 - which doesn't even make sense to me - the text is moved to the bottom of the canvas but still squished flat. There's definitely something about positioning here that I don't understand. How can I get text in the canvas that is the height I specify?

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

ctx.font = "48px Arial";
ctx.fillText("Hello World", 0, 64);
<canvas id="cv" style="border: 1px solid black; height: 64px; width: 300px;"></canvas>

Upvotes: 0

Views: 2270

Answers (1)

DBS
DBS

Reputation: 9959

You're not giving your canvas an initial size, you need to pass in the size properties (CSS sizes are actually different, you can have a 1000 pixel wide canvas shown at 10 pixels wide on-screen)

Just add width="300" height="64" to the canvas element

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

ctx.font = "48px Arial";
ctx.fillText("Hello World", 0, 48);
<canvas 
  id="cv"
  style="border: 1px solid black; height: 64px; width: 300px;"
  width="300"
  height="64"
></canvas>

To clarify, your text was actually being written correctly to the canvas, but your canvas was not at the same aspect ratio as the CSS that was displaying it, leading to the squashed effect you are seeing.

Upvotes: 5

Related Questions