Text2D.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { DoubleSide, Mesh, MeshBasicMaterial, PlaneGeometry, Texture } from 'three';
  2. /** @module Text2D */
  3. /**
  4. * A helper function for creating a simple plane mesh
  5. * that can be used as a text label. The mesh's material
  6. * holds a canvas texture that displays the given message.
  7. *
  8. * @param {string} message - The message to display.
  9. * @param {number} height - The labels height.
  10. * @return {Mesh} The plane mesh representing a text label.
  11. */
  12. function createText( message, height ) {
  13. const canvas = document.createElement( 'canvas' );
  14. const context = canvas.getContext( '2d' );
  15. let metrics = null;
  16. const textHeight = 100;
  17. context.font = 'normal ' + textHeight + 'px Arial';
  18. metrics = context.measureText( message );
  19. const textWidth = metrics.width;
  20. canvas.width = textWidth;
  21. canvas.height = textHeight;
  22. context.font = 'normal ' + textHeight + 'px Arial';
  23. context.textAlign = 'center';
  24. context.textBaseline = 'middle';
  25. context.fillStyle = '#ffffff';
  26. context.fillText( message, textWidth / 2, textHeight / 2 );
  27. const texture = new Texture( canvas );
  28. texture.needsUpdate = true;
  29. const material = new MeshBasicMaterial( {
  30. color: 0xffffff,
  31. side: DoubleSide,
  32. map: texture,
  33. transparent: true,
  34. } );
  35. const geometry = new PlaneGeometry(
  36. ( height * textWidth ) / textHeight,
  37. height
  38. );
  39. const plane = new Mesh( geometry, material );
  40. return plane;
  41. }
  42. export { createText };
粤ICP备19079148号