Skip to content

Instantly share code, notes, and snippets.

@hoiheart
Last active October 29, 2020 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoiheart/c87a0cca8d3c1f0b3f0c451fb7d591d9 to your computer and use it in GitHub Desktop.
Save hoiheart/c87a0cca8d3c1f0b3f0c451fb7d591d9 to your computer and use it in GitHub Desktop.
getUnicodeRanges
const opentype = require('opentype.js')
const getUnicodeRanges = function (fontSource) {
// 유니코드 포맷으로 변환
const formatUnicode = (unicode) => {
unicode = unicode.toString(16)
if (unicode.length > 4) {
return ('000000' + unicode.toUpperCase()).substr(-6)
} else {
return ('0000' + unicode.toUpperCase()).substr(-4)
}
}
const font = opentype.loadSync(fontSource)
const glyphs = []
for (let i = 0; i < font.glyphs.length; i++) {
const glyph = font.glyphs.get(i)
if (glyph.unicode !== undefined && glyph.xMin !== undefined) { // 유니코드와 글자 모양(x 좌표가 있는 경우)이 존재하면 실제 글리프로 판단
glyphs.push(glyph.unicode)
}
}
const unicodes = [] // unicode-range 를 만들기 위한 배열
glyphs.sort((a, b) => a - b).map((unicode, index) => { // unicode-range 를 위해 코드값을 숫자 순서별로 정렬
if (!glyphs[index - 1] || !glyphs[index + 1]) { // 이전과 다음이 없다면 유니코드로 추가
unicodes.push('U+' + formatUnicode(unicode))
} else if (unicode - 1 === glyphs[index - 1] && unicode + 1 === glyphs[index + 1]) { // 이전과 다음이 이어진다면 - 로 추가
unicodes.push('-')
} else { // 그 외도 유니코드로 추가
unicodes.push('U+' + formatUnicode(unicode))
}
return unicode
})
// 배열을 합치면 U+0000,U+0002,-,-,-,U+0006,U+0007 형태이며 ,-,-, 패턴을 - 로 변경하여 U+0000,U+0002-U+0006,U+0007 로 CSS에서 사용할 수 있는 코드로 리턴
return unicodes.join(',').replace(/(?:,-(,-)*,U\+)/gm, '-').replace(/,/g, ', ')
}
const ranges = getUnicodeRanges('./NanumSquareR.ttf')
console.log(ranges)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment