【问题标题】:How do I add custom font to sprite如何将自定义字体添加到精灵
【发布时间】:2018-03-09 13:39:43
【问题描述】:

据我所知,我只能在创建 Sprite 时使用 Arial。其他字体不起作用。有没有办法添加像Roboto这样的自定义字体?

代码:

const makeTextSprite = (_text, properties) => {
    const text = _text;
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    context.translate(0.5, 0.5);
    const metrics = context.measureText(text);
    const textWidth = metrics.width;

    context.font = properties.font;
    context.fillStyle = properties.fillStyle;
    context.strokeStyle = properties.strokeStyle;
    context.lineWidth = properties.lineWidth;

    context.fillText(text, 125, 75);

    const texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;
    return texture;
};

componentDidMount() {
   const properties = {
        font: '5px Arial',
        fillStyle: 'rgb(142, 142, 142)',
        strokeStyle: 'rgba(255,0,0,1)',
        lineWidth: 4,
    };

    const texture1 = makeTextSprite('Text Here', properties);

    this.spriteMaterial1.map = texture1;
}

render() {
    return 
        <React3
          mainCamera="camera" // this points to the perspectiveCamera which has the name set to "camera" below
          width={canvasWidth}
          height={canvasHeight}
          clearColor={'#ffffff'}
          antialias
        >
        <scene ref={(ref) => { this.scene = ref; }}>
            <perspectiveCamera
              name="camera"
              fov={45}
              aspect={canvasWidth / canvasHeight}
              near={1}
              far={1000}
              position={this.cameraPosition}
              ref={(ref) => { this.camera = ref; }}
            />

            <sprite position={this.position1} scale={this.scale} >
                <spriteMaterial ref={(ref) => { this.spriteMaterial1 = ref; }} />
            </sprite>
        </scene>
    </React3>
   }

properties 中,我尝试将Ariel 替换为Roboto,但没有成功。有什么想法吗?

上面的代码(只是写了相关部分)工作并给了我Ariel的字体。 (虽然有点模糊。想知道如何获得清晰的文本)

【问题讨论】:

    标签: javascript reactjs fonts three.js


    【解决方案1】:

    为了在画布中使用外部字体,您需要确保在调用 ctx.fillText() 时它们已经加载。

    仅仅@font-face 是不够的,因为它只是告诉浏览器在哪里可以找到它,如果它想加载它。但除非 HTML 中有实际内容使用该字体,否则浏览器不会加载该文件。

    对于 Firefox 和 Chrome,您可以使用字体加载 API。或者,使用 https://fontfaceobserver.com/ 之类的东西来检测字体何时准备就绪。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多