#
luxiaotao1123
2024-04-26 73e5e4f17c23a7f4832ea2bb36e1bd3799ab9ad9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import * as THREE from 'three';
import { useEffect, useState } from 'react';
 
function generateSprite(text, color, fontSize = 50) {
  const canvas = document.createElement('canvas');
  canvas.width = 300;
  canvas.height = 300;
  const context = canvas.getContext('2d');
  context.beginPath();
  context.font = `${fontSize}px Microsoft YaHei`;
  context.fillStyle = color;
  context.textAlign = 'center';
  context.textBaseline = 'middle';
  context.fillText(text, canvas.width / 2, canvas.height / 2);
  context.fill();
  context.stroke();
  return canvas;
}
 
const Text = (props) => {
  const { text, position, color = '#00D1D1', fontSize = 100 } = props;
 
  const [material, setMaterial] = useState(undefined);
  const [scale, setScale] = useState(new THREE.Vector3(100, 100, 100));
 
  useEffect(() => {
    const canvas = generateSprite(text, color, fontSize);
    const texture = new THREE.CanvasTexture(canvas);
    setScale(new THREE.Vector3(texture.image.width / 4, texture.image.height / 4, 1));
    const material = new THREE.SpriteMaterial({
      map: texture,
      blending: THREE.AdditiveBlending,
    });
    setMaterial(material);
  }, [text, color, fontSize]);
 
  return <sprite material={material} position={position} scale={scale} />;
}
 
export default Text;