【问题标题】:How to integrate Fontawesome 6 Pro self hosted icons with HTML5 canvas?如何将 Fontawesome 6 Pro 自托管图标与 HTML5 画布集成?
【发布时间】:2023-01-03 11:58:44
【问题描述】:

我有一个 React 项目,并在 this guide 之后自行托管字体

我的文件夹如下所示:

src
|___fonts
|   |___css
|   |   |___fontawesome.css
|   |   |___regular.css
|   |___webfonts
|       |___fa-regular-400.woff2
|       |___fa-regular-400.ttf
|___App.css
|___App.ts
|___...

在我的 App.js 中,我有以下代码:

import React, {useLayoutEffect, useRef} from 'react';
import './App.css';
import './fonts/css/fontawesome.css';
import './fonts/css/regular.css';
function App() {

  const canvasRef = useRef<HTMLCanvasElement>(null);
  let ctx: CanvasRenderingContext2D;
  let canvas: HTMLCanvasElement;
  useLayoutEffect(() => {
    canvas = canvasRef.current as HTMLCanvasElement;
    ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
    draw();
  }, []);

  const draw = (): void => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.font = '100px Font Awesome 6 Pro';
    ctx.fillText('\uf111', 100, 100);
    requestAnimationFrame(draw);
  }

  return (
    <div className="App">
      <canvas id={'game_canvas'} ref={canvasRef} width={500} height={500}>Your browser doesn't support canvas.</canvas>
      <p>&#xf111;</p>
    </div>
  );
}

export default App.ts;

在 App.css 里面

.App {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Font Awesome 6 Pro';
}
.App #game_canvas {
  border: 1px solid red;
}

请注意,在画布之后,我正在渲染一个 &lt;p&gt;&lt;/p&gt; 标签。该标记使用 unicode 的 HTML 语法,而在 ctx.fillText 函数中我使用的是其他语法。

结果是我看到了在 &lt;p&gt;&lt;/p&gt; 标签中呈现的图标,但没有看到画布上下文中的图标。

Inside canvas the icon is broken, but the fa-circle-icon can be seen outside

我尝试交替使用几种 unicode 语法,并将排版与 this guide 之后的 Styled 组件集成,但没有很好的结果。

预期的行为是能够在画布 2D 上下文中呈现来自自托管网络字体的图标。

【问题讨论】:

    标签: css html5-canvas font-awesome webfonts


    【解决方案1】:

    找到问题了!,我只是忘记了定义 ctx.font 属性的字体名称中的双引号

    ctx.font = '100px Font Awesome 6 Pro' //wrong
    ctx.font = '100px "Font Awesome 6 Pro"' //correct
    

    仔细查看时发现问题:How can I use FontAwesome icons on a html 5 canvas

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 2020-12-02
      • 2020-01-28
      • 2015-04-03
      • 2011-07-22
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多