canvas 引入外部字体不生效解决方法
canvas 引入外部字体方法:
1、在css中引入外部字体
<style>
@font-face {
font-family: "myFont";
src: url("./myFont.ttf");
/* 省略其他格式 */
}
</style>
2、在js中引用
window.onload = function () {
const cvs = document.getElementById('canvas');
const ctx = cvs.getContext('2d');
var devicePixelRatio = window.devicePixelRatio || 1
var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1
var ratio = devicePixelRatio / backingStoreRatio
var oldWidth = canvas.width;
var oldHeight = canvas.height;
canvas.width = oldWidth * ratio;
canvas.height = oldHeight * ratio;
ctx.beginPath();
ctx.fillStyle = 'red';// 设置填充画笔颜色为红色,即字体颜色
ctx.font = '28px myFont';// 设置字体大小
ctx.fillText('the', 50, 50);// 绘制 "实心" 文字
ctx.closePath();
}
本以为万事大吉,在浏览器运行完,没有任何改变

万能的百度君上线,通过在dom标签里加上一个使用此字体的标签且内容不能为空如下:
<div style="font-family: myFont;visibility: hidden;font-size: 0;">1</div>

达到目的。
浙公网安备 33010602011771号