font.ts 1021 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * 判断操作系统是否存在某字体
  3. * @param fontName 字体名
  4. */
  5. export const isSupportFont = (fontName: string) => {
  6. if (typeof fontName !== 'string') return false
  7. const arial = 'Arial'
  8. if (fontName.toLowerCase() === arial.toLowerCase()) return true
  9. const size = 100
  10. const width = 100
  11. const height = 100
  12. const str = 'a'
  13. const canvas = document.createElement('canvas')
  14. const ctx = canvas.getContext('2d', { willReadFrequently: true })
  15. if (!ctx) return false
  16. canvas.width = width
  17. canvas.height = height
  18. ctx.textAlign = 'center'
  19. ctx.fillStyle = 'black'
  20. ctx.textBaseline = 'middle'
  21. const getDotArray = (_fontFamily: string) => {
  22. ctx.clearRect(0, 0, width, height)
  23. ctx.font = `${size}px ${_fontFamily}, ${arial}`
  24. ctx.fillText(str, width / 2, height / 2)
  25. const imageData = ctx.getImageData(0, 0, width, height).data
  26. return [].slice.call(imageData).filter(item => item !== 0)
  27. }
  28. return getDotArray(arial).join('') !== getDotArray(fontName).join('')
  29. }