-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path生成字体子集.js
81 lines (64 loc) · 2.21 KB
/
生成字体子集.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const replaceSVG = text=>{
text = text.replace(/ transform="matrix\(1 0 0 1 (\d+) (\d+)\)" class=".+"/,' x="$1" y="$2"')
return text;
};
let fontAPI = `https://lab.magiconch.com/api/fontmin`;
const generateFontURL = (name,text)=>{
text += '0';
text = text.replace(/\s/g,'');
text = Array.from(new Set(text)).sort().join('');
if(!text) return requestAnimationFrame(onOver);
console.log(text);
const unicode = str2utf8(text).join();
const fontURL = `${fontAPI}?name=${name}&unicode=${unicode}&type=woff`;
return fontURL;
};
const getFontFromText = (name,text,onOver=_=>{})=>{
const fontURL = generateFontURL(name,text);
loadFont(name,fontURL,_=>{
onOver(_)
})
};
const loadFont = async (fontName,fontURL,callback) => {
const fontFace = new FontFace(fontName, `url(${fontURL})`);
fontFace.load().then(fontFace => {
document.fonts.add(fontFace);
callback(fontFace);
}).catch(e=>{
callback();
})
};
function str2utf8(str) {
return str.split('').map(s=>s.charCodeAt(0))
}
function utf82str(str) {
return String.fromCharCode.apply(null,Array.from(str))
};
const { readFileSync, writeFileSync } = require('fs');
const getTextFromHTMLFile = (filename)=>{
let html = readFileSync(filename,'utf8');
const texts = [];
const addTextFromMatch = (all,text)=>{
text = text.replace(/<.+?>/g,'');
texts.push(text);
return '';
}
html = html.replace(/<(?:path|rect) id="(.+?)"/g,addTextFromMatch);
html = html.replace(/<text .+?>(.+?)<\/text>/g,addTextFromMatch);
html = html.replace(/<a .+?>(.+?)<\/a>/g,addTextFromMatch);
html = html.replace(/<h2 .+?>(.+?)<\/h2>/g,addTextFromMatch);
html = html.replace(/<p>([\s\S]+?)<\/p>/g,addTextFromMatch);
return texts.join('');
};
const defaultText = `1234567890:`;
const text = defaultText + getTextFromHTMLFile('html/index.html') + getTextFromHTMLFile('china-ex.svg');
const fontURL = generateFontURL(`JiaLiDaYuanJF`,text);
const axios = require('axios');
const downFontFile = async _=>{
let r = await axios.get(fontURL,{
responseType: 'arraybuffer'
});
console.log(r.data);
writeFileSync('html/字体.woff',r.data,'binary');
};
downFontFile();