简体   繁体   中英

How do I add custom font to sprite

As far as I'm aware I can only use Arial when creating a Sprite . The other fonts do not work. Is there a way to add custom fonts like Roboto ?

Code:

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>
   }

In properties I tried replacing Ariel with Roboto but it did not work. Any ideas?

The code above (just wrote the relevant parts) works and gives me font in Ariel . (It is a bit blurry though. Would like to know how to get crisp clear text as well)

In order to use external fonts in the canvas you need to make sure that they are already loaded when calling ctx.fillText() .

Just the @font-face is not enough as it just tells the browser where to find it IF it wants to load it. But unless there is actual content in the HTML that uses the font, the browser will not load the file.

For Firefox and Chrome there is the font-loading API that you could use instead. Alternatively, use something like https://fontfaceobserver.com/ to detect when the font is ready.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM