在canvas元素中使用自定义@font-face
,在DOM中渲染得很好,当通过canvas渲染时,它会垂直拉伸(stretch)文本。或者可能会水平挤压它,无法判断。
CSS:
@font-face {
font-family: 'myFont';
src: url('myFont.ttf');
}
Canvas 元素宽度通过 CSS 设置为其父元素(300x250px 正方形)的 100%,文本通过以下方式添加到 Canvas :
cContext.fillStyle = "rgba(255,255,255,1)";
cContext.font = '58px "myFont"';
cContext.fillText("1000", 22, 71);
最佳答案
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>
来自@pointy 评论的示例。 要指定 canvas 元素的宽度和高度,您应该使用元素的属性而不是 css。
如果你想调整 Canvas 的大小,你应该在 JS 中这样做,如下所示 Resize HTML5 canvas to fit window
关于javascript - Canvas 自定义字体渲染错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29301375/