CircleTextLabel.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import * as THREE from "three";
  2. import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";
  3. import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js";
  4. import { LineGeometry } from "three/examples/jsm/lines/LineGeometry.js";
  5. export default class CircleTextLabel extends THREE.Mesh {
  6. constructor(text, outline) {
  7. let res = 5;
  8. const canvas = document.createElement("canvas");
  9. canvas.width = 128 * res;
  10. canvas.height = 128 * res;
  11. let fontSize = 68 * res;
  12. const ctx = canvas.getContext("2d");
  13. ctx.font = `800 ${fontSize}px Arial`; // 设置字体大小和类型
  14. ctx.textAlign = "center";
  15. ctx.textBaseline = "middle";
  16. ctx.fillStyle = "#e44d54"; // 设置文字颜色和透明度
  17. ctx.fillText(text, canvas.width / 2, canvas.height / 2);
  18. // 步骤3: 将画布转换为纹理
  19. const texture = new THREE.CanvasTexture(canvas);
  20. // 步骤4: 创建材质并应用纹理
  21. const m = new THREE.MeshBasicMaterial({
  22. map: texture,
  23. transparent: true, // 允许材质透明
  24. });
  25. // const canvas_map = new THREE.Texture(canvas);
  26. texture.colorSpace = THREE.SRGBColorSpace;
  27. texture.needsUpdate = true;
  28. texture.anisotropy = 4;
  29. const g = new THREE.CircleGeometry(0.08, 128);
  30. g.rotateX(-Math.PI / 2);
  31. super(g, m);
  32. this.userData = text;
  33. const edges = new THREE.EdgesGeometry(g, 50);
  34. const geometry = new LineGeometry();
  35. geometry.fromEdgesGeometry(edges);
  36. const line_m = new LineMaterial({
  37. color: 0xe44d54,
  38. linewidth: 5,
  39. });
  40. line_m.resolution.set(window.innerWidth, window.innerHeight);
  41. const line_n = new LineSegments2(geometry, line_m);
  42. line_n.position.y += 0.5;
  43. this.add(line_n);
  44. this.name = "circle_" + text;
  45. }
  46. }