totoaussi
totoaussi

Reputation: 731

font size don't work in canvas when setting the canvas width

when I set the width canvas, the fontSize in the canvas is not correct (too small) and i don't know why.

Here my source code :

<canvas id="canvas"></canvas>
<script type="text/javascript">
c = document.getElementById("canvas");
ctx = c.getContext("2d"); 

text = "Test";
ctx.font = "normal 12px sans-serif";
c.width = 200;
ctx.fillText(text, 0, 20);
</script>

Have you an idea ?

Thank you in advance, cordially.

Upvotes: 1

Views: 470

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206508

You first need to set the desired canvas width.
Otherwise a 12px font will be first painted on a 300px (default width) canvas. If you resize the canvas AFTER the text is already in context, logically the text will end up smaller since the canvas size changed to 200 afterwards.

c = document.getElementById("canvasa");
c.width = 200; // HERE!!!!!!
ctx = c.getContext("2d"); 


text = "Test";
ctx.font = "normal 12px sans-serif";
ctx.fillText(text, 0, 20);
<canvas id="canvasa"></canvas>

Upvotes: 1

Related Questions