Steve U
Steve U

Reputation: 15

Canvas custom font renders wrong

Using a custom @font-face within a canvas element, renders fine in DOM, when rendered through canvas it stretches the text vertically. Or might be squashing it horizontally, cannot tell.

CSS:

@font-face {
    font-family: 'myFont';
    src: url('myFont.ttf');
}

Canvas element width is set to 100% of its parent (a 300x250px square) through CSS, text is added to canvas by:

cContext.fillStyle = "rgba(255,255,255,1)";
cContext.font = '58px "myFont"';
cContext.fillText("1000", 22, 71);

enter image description here

Upvotes: 0

Views: 859

Answers (1)

corn3lius
corn3lius

Reputation: 4985

 

var c = document.getElementById("square");
var ctx = c.getContext("2d");;
ctx.font = "40px Arial";
ctx.fillStyle = "#FF0000";
ctx.fillText("1000",40,80);

var c2 = document.getElementById("notsquare");
var ctx2 = c2.getContext("2d");;
ctx2.font = "40px Arial";
ctx2.fillStyle = "#FF0000";
ctx2.fillText("1000",40,60);
#square, #notsquare{
  border: 1px solid red;
  }
#notsquare{ 
  width: 300px;
  height: 400px;
  left:0px;
}
<canvas id='square' width='300' height='300' ></canvas>
<canvas id='notsquare' width='300' height='300' ></canvas>

Example from @pointy remark. To specify the width and height of the canvas element you should use the attributes of the element and not css.

if you want to resize the canvas you should do so in the JS like this Resize HTML5 canvas to fit window

Upvotes: 1

Related Questions