Text2D.js 1018 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import * as THREE from 'three';
  2. function createText( message, height ) {
  3. const canvas = document.createElement( 'canvas' );
  4. const context = canvas.getContext( '2d' );
  5. let metrics = null;
  6. const 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. const material = new THREE.MeshBasicMaterial( {
  20. color: 0xffffff,
  21. side: THREE.DoubleSide,
  22. map: texture,
  23. transparent: true,
  24. } );
  25. const geometry = new THREE.PlaneGeometry(
  26. ( height * textWidth ) / textHeight,
  27. height
  28. );
  29. const plane = new THREE.Mesh( geometry, material );
  30. return plane;
  31. }
  32. export { createText };