判断字体是否可用
js
/**
* 判断浏览器是否支持字体
* @param {string} font 字体名称
* @returns {boolean} 是否支持
* @example
* const flag = isSupportFontFamily('微软雅黑')
* if(flag) console.log('支持微软雅黑字体')
* else console.log('不支持微软雅黑字体')
*/
function isSupportFontFamily(font) {
const defaultFont = "Arial";
if (font.toLowerCase() == defaultFont.toLowerCase()) return true;
const character = "a";
const fontSize = 100;
const width = 100;
const height = 100;
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d", { willReadFrequently: true });
canvas.width = width;
canvas.height = height;
context.textAlign = "center";
context.fillStyle = "black";
context.textBaseline = "middle";
const drawFont = (font) => {
context.clearRect(0, 0, width, height);
context.font = fontSize + "px " + font + ", " + defaultFont;
context.fillText(character, width / 2, height / 2);
const imageData = context.getImageData(0, 0, width, height).data;
return Array.from(imageData).filter((element) => element != 0);
};
return drawFont(defaultFont).join("") !== drawFont(font).join("");
}
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
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