-
Notifications
You must be signed in to change notification settings - Fork 29
Usage Canvas
江夏尧 edited this page Jan 13, 2025
·
1 revision
Q: 为啥 Canvas 里面使用 font-family 并没有渲染到字体?
A: 因为 Canvas 本质是一个画布,绘制上去的东西,并不能更改。浏览器能够识别到你使用的 font-family 和文本直接渲染上去了备用字体,但是下载 font-family 指定的字体需要时间。所以,一般都有框架进行自动刷新,保证渲染正确。
检测到 document.fonts.onloadingdone
事件,则让框架进行一个重新更新。
// 监听字体加载完成事件
document.fonts.onloadingdone = () => {
canvas._objects.forEach(i => {
if (i.fontFamily === "YEFONTXiaoShiTou")
// 标记这个节点为脏数据,renderAll 会自动绘制节点
i._forceClearCache = true
})
// 重绘制
canvas.renderAll();
}
document.fonts.onloadingdone = () => {
leafer.forceUpdate()
}
document.fonts.onloadingdone = () => {
updateTextElements(app.stage)
};
function updateTextElements(stage) {
function traverseChildren(container) {
container.children.forEach(child => {
if (child instanceof Text) {
child.updateText();
}
if (child.children && child.children.length > 0) {
traverseChildren(child);
}
});
}
traverseChildren(stage);
}
https://github1s.com/KonghaYao/cn-font-bundler-demo/blob/canvas-usage/pixijs.html#L47-L62