threeJs 创建文字方式
一,使用 TextGeometry创建3D文字
1.需加载字体配合使用,使用THREE.FontLoader
// 加载字体 loadFont() { return new Promise(function (resolve, reject) { const loader = new THREE.FontLoader(); loader.load( './helvetiker.json', function ( response ) { try { resolve(response) } catch(error) { reject(error) } }); }) }
注意:如果出现中文乱码问题,需挑选中文字体文件再转换成json使用,转换地址:http://gero3.github.io/facetype.js
2,使用 TextGeometry添加
const font = await this.loadFont() fontOption = { font: font, size: 0.5, height: 0, curveSegments: 1, bevelThickness: 1, bevelSize: 0, bevelEnabled: false, bevelSegments: 0, }; let txtMater = new THREE.MeshBasicMaterial({color: 0xffffff}); const txtGeo1 = new THREE.TextGeometry('你好123', fontOption); let txtMesh1 = new THREE.Mesh(txtGeo1, txtMater); txtMesh1.position.set(0, 0, 8); this.scene.add(txtMesh1);
二、使用CanvasTexture + Sprite生成文字
let canvas = document.createElement('canvas'); canvas.width = 400; canvas.height = 200; const context = canvas.getContext('2d'); context.font = '60px Microsoft YaHei'; context.textAlign = 'center'; context.fillStyle = '#ffffff'; const text = '宽度:1.2' const textWidth = context.measureText(text).width context.fillText(text, textWidth / 2, 80); const texture = new THREE.CanvasTexture(canvas); texture.needsUpdate = true; const textSprit = new THREE.Sprite(new THREE.SpriteMaterial({map: texture, color: 0xffffff})); textSprit.position.set(0, 0, 8); textSprit.scale.set(2, 2, 2) this.scene.add(textSprit);