let can = document.createElement('canvas') can.width = 300 can.height = 350 var str1 = window.xyjVue.$waterStr; let cans = can.getContext('2d') cans.rotate(-25 * Math.PI / 180) const fontSize = 16; const opacity = 0.4; document.fonts.ready.then(() => { // 设置字体 const font = new FontFace('CustomFont', 'url(http://hnxyjwork.kmdns.net:15002/wenYi/DIN-Light.woff)'); font.load().then(() => { cans.fillStyle = `rgba(216, 216, 216, ${opacity})`; // 设置文本颜色和透明度 cans.font = `16px CustomFont`;// 设置字体大小和名称 cans.fillText(str1, 0, 300) cans.fillText(str1, 0, 130) let div = document.createElement('div') div.id = id div.style.pointerEvents = 'none' div.style.top = '0' div.style.left = '0' div.style.right = '0' div.style.bottom = '0' div.style.opacity = '1' div.style.position = 'absolute' div.style.zIndex = 7 div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat fixed' let img = new Image(); img.src = can.toDataURL('image/png'); img.onload = function () { div.style.background = `url(${img.src}) left top repeat fixed`; if (parentName) { document.querySelector(parentName).appendChild(div); } else { document.body.appendChild(div); } }; }); });字体文件虽然引入了 但是页面并不生效
时间: 2024-04-23 09:24:38 浏览: 131
document.createElement("A")比较不错的属性
这个问题可能是由于字体文件加载时还未完成,就已经开始绘制文字导致的。你可以尝试在字体文件加载完成后再进行绘制,或者在绘制之前先判断字体文件是否已经加载完成。
你可以修改代码如下:
```
let can = document.createElement('canvas');
can.width = 300;
can.height = 350;
var str1 = window.xyjVue.$waterStr;
let cans = can.getContext('2d');
cans.rotate(-25 * Math.PI / 180);
const fontSize = 16;
const opacity = 0.4;
// 设置字体
const font = new FontFace('CustomFont', 'url(http://hnxyjwork.kmdns.net:15002/wenYi/DIN-Light.woff)');
font.load().then(() => {
document.fonts.add(font); // 添加字体
cans.fillStyle = `rgba(216, 216, 216, ${opacity})`; // 设置文本颜色和透明度
cans.font = `${fontSize}px CustomFont`; // 设置字体大小和名称
cans.fillText(str1, 0, 300);
cans.fillText(str1, 0, 130);
let div = document.createElement('div');
div.id = id;
div.style.pointerEvents = 'none';
div.style.top = '0';
div.style.left = '0';
div.style.right = '0';
div.style.bottom = '0';
div.style.opacity = '1';
div.style.position = 'absolute';
div.style.zIndex = 7;
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat fixed';
let img = new Image();
img.src = can.toDataURL('image/png');
img.onload = function () {
div.style.background = `url(${img.src}) left top repeat fixed`;
if (parentName) {
document.querySelector(parentName).appendChild(div);
} else {
document.body.appendChild(div);
}
};
});
```
这样就可以在字体加载完成后再进行绘制,确保绘制出的文字使用的是正确的字体。
阅读全文