fonts.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { SystemFont } from "@/types/common"
  2. /**
  3. * 判断操作系统是否存在某字体
  4. * @param fontName 字体名
  5. */
  6. export const getSupportFonts = (fontNames: SystemFont[]) => {
  7. let supportFonts: SystemFont[] = []
  8. const size = 100
  9. const width = 100
  10. const height = 100
  11. const str = 'a'
  12. const canvas = document.createElement('canvas')
  13. const ctx = canvas.getContext('2d', { willReadFrequently: true })
  14. if (!ctx) return supportFonts
  15. canvas.width = width
  16. canvas.height = height
  17. ctx.textAlign = 'center'
  18. ctx.fillStyle = 'black'
  19. ctx.textBaseline = 'middle'
  20. return fontNames.filter(item => {
  21. if (typeof item.value !== 'string') return false
  22. const arial = 'Arial'
  23. if (item.value.toLowerCase() === arial.toLowerCase()) return true
  24. const getDotArray = (_fontFamily: string) => {
  25. ctx.clearRect(0, 0, width, height)
  26. ctx.font = `${size}px ${_fontFamily}, ${arial}`
  27. ctx.fillText(str, width / 2, height / 2)
  28. const imageData = ctx.getImageData(0, 0, width, height).data
  29. return [].slice.call(imageData).filter(item => item !== 0)
  30. }
  31. return getDotArray(arial).join('') !== getDotArray(item.value).join('')
  32. })
  33. }
  34. export async function loadFont(fontFamily: string) {
  35. let font
  36. try {
  37. const fonts = window.queryLocalFonts();
  38. font = fonts.filter(item => item.family === fontFamily)[0]
  39. } catch(e: any) {
  40. console.log(`Cannot query fonts: ${e.message}`)
  41. } finally {
  42. return font
  43. }
  44. }