Text2D.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import * as THREE from "../../../build/three.module.js";
  2. function createText(message, height) {
  3. const canvas = document.createElement("canvas");
  4. const context = canvas.getContext("2d");
  5. let metrics = null,
  6. textHeight = 100;
  7. context.font = "normal " + textHeight + "px Arial";
  8. metrics = context.measureText(message);
  9. const textWidth = metrics.width;
  10. canvas.width = textWidth;
  11. canvas.height = textHeight;
  12. context.font = "normal " + textHeight + "px Arial";
  13. context.textAlign = "center";
  14. context.textBaseline = "middle";
  15. context.fillStyle = "#ffffff";
  16. context.fillText(message, textWidth / 2, textHeight / 2);
  17. const texture = new THREE.Texture(canvas);
  18. texture.needsUpdate = true;
  19. //var spriteAlignment = new THREE.Vector2(0,0) ;
  20. const material = new THREE.MeshBasicMaterial({
  21. color: 0xffffff,
  22. side: THREE.DoubleSide,
  23. map: texture,
  24. transparent: true,
  25. });
  26. const geometry = new THREE.PlaneGeometry(
  27. (height * textWidth) / textHeight,
  28. height
  29. );
  30. let plane = new THREE.Mesh(geometry, material);
  31. return plane;
  32. }
  33. export { createText };