问题描述:在使用blob对象读取字体文件时,可能会出现无法识别字体文件类型的错误。
解决方法:可以尝试使用FileReader对象来读取字体文件,并将其转换为base64编码。以下是一个示例代码:
function readFileAsDataURL(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
function loadFont(blob) {
return new Promise((resolve, reject) => {
const font = new FontFace('CustomFont', 'url(' + URL.createObjectURL(blob) + ')');
font.load()
.then(() => {
document.fonts.add(font);
resolve();
})
.catch(reject);
});
}
// 读取字体文件
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
readFileAsDataURL(file)
.then(dataUrl => {
// 将字体文件转换为blob对象
const base64Font = dataUrl.split(',')[1];
const fontBlob = b64toBlob(base64Font, 'application/octet-stream');
// 加载字体
return loadFont(fontBlob);
})
.then(() => {
console.log('字体加载成功!');
})
.catch(error => {
console.error('字体加载失败:', error);
});
// base64字符串转换为blob对象
function b64toBlob(b64Data, contentType='application/octet-stream', sliceSize=512) {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
上述代码中,首先通过FileReader对象将字体文件转换为base64编码的字符串。然后,将base64字符串转换为blob对象,使用FontFace API加载字体文件。最后,将加载的字体添加到document.fonts中。
请注意,以上代码仅适用于现代浏览器,部分旧版浏览器可能不支持FontFace API。