2017-09-27 24 views
0

Spriteを作成するときは、Arialしか使用できません。他のフォントは機能しません。 Robotoのようなカスタムフォントを追加する方法はありますか?スプライトにカスタムフォントを追加する方法

コード:properties

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

私はRobotoArielを交換しようとしたが、それはうまくいきませんでした。何か案は?

上記のコード(関連部分を書きました)は動作し、Arielに私のフォントを与えます。

答えて

0

キャンバスで外部フォントを使用するには、ctx.fillText()を呼び出すときに、それらが既に読み込まれていることを確認する必要があります。

ちょうど@font-faceはブラウザに、ロードしたい場所がどこにあるかを伝えるだけで十分ではありません。しかし、フォントを使用するHTMLに実際のコンテンツがない限り、ブラウザはファイルをロードしません。

FirefoxとChromeには、代わりに使用できるフォント読み込みAPIがあります。あるいは、フォントがいつ用意されているかを検出するのに、https://fontfaceobserver.com/のようなものを使用します。

関連する問題