JS-检测字体

一、实现原理

根据用户设置的字体将某一个字符绘制在canvas上(fillText()),并提取像素信息(getImageData()),然后和默认字体进行比对如果像素不一致,说明字体生效,说明字体不生效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
let isSupportFontFamily = function(fontFamily) {
if (typeof fontFamily !== 'string') {
return false;
}


let defaultFontFamily = 'Arial';
if (fontFamily.toLowerCase() === defaultFontFamily.toLowerCase()) {
return true;
}


let defaultLetter = 'a';
let defaultFontSize = 100;


// 使用该字体绘制的canvas
let width = 100;
let height = 100;
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;


// 全局一致的绘制设定
context.textAlign = 'center';
context.fillStyle = 'black';
context.textBaseline = 'middle';


let getFontData = function(fontFamily) {
context.clearRect(0, 0, width, height);
context.font = defaultFontSize + 'px ' + fontFamily + ', ' + defaultFontFamily;
context.fillText(defaultLetter, width / 2, height / 2);
let data = context.getImageData(0, 0, width, height).data;
return [].slice.call(data).filter(function(value) {
return value !== 0;
});
};

return getFontData(defaultFontFamily).join('') !== getFontData(fontFamily).join('');
};