广树
2024-11-21 16:04
@hikari:BGM也许是吧,歌曲部分感觉不一定
作者:广树时间:2021-11-01 20:08:20分类:JavaScript/jQuery/Vue
有时候在绘制canvas的时候可能会用到一些特殊字体。而中文字体例如是用类似谷歌字体加载的话,可能会是分段加载,DOM不一定会加载过某些字体从而导致在绘制canvas时出现字体缺失。
这个时候可以使用如下代码预加载css中的字体
document.fonts.load
实际使用案例:
const loadTextFont = async (fontSize, text) => { await document.fonts.load(`${fontSize}px Noto Sans SC`, text).catch((e) => { console.error(e); }); }; const writeText = (text, fontSize, color, shadow, x, y, context) => { context.fillStyle = color; context.textBaseline = "middle"; context.textAlign = "center"; context.font = `${fontSize}px Noto Sans SC`; const res = context.measureText(text); if (shadow) { context.shadowBlur = 3; context.shadowColor = "black"; context.strokeText(text, x, y); } context.fillText(text, x, y); return res; }; const init = async (canvas,loadFont,title,fontSize) => { canvas.width = 396; canvas.height = 32; const context = canvas.getContext("2d"); if(loadFont){ await loadTextFont(fontSize, title); } const titleRes = writeText( title, fontSize, "#ffffff", true, 202, 15, context ); }; init(document.getElementById("canvas2"),false,"不预先加载思源字体","28"); init(document.getElementById("canvas"),true,"思源字体预加载","28");