Text2D.js 1.4 KB

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