如何获取troika-three-text中Text对象的宽度与高度?
获取troika-three-text中Text对象的宽度与高度
要获取Text对象的宽高,必须确保文本布局计算完成——也就是要先调用sync()方法(或等待它自动完成异步渲染),因为文本的尺寸是在布局阶段异步计算的。以下是几种可靠的实现方式:
方法1:使用getRenderedBounds()方法
这个方法会返回文本实际渲染区域的边界框对象,包含min和max坐标属性,通过坐标差值即可得到宽高:
// 等待sync异步完成,确保布局计算完毕 await myText.sync() const bounds = myText.getRenderedBounds() const width = bounds.max.x - bounds.min.x const height = bounds.max.y - bounds.min.y console.log('文本宽度:', width) console.log('文本高度:', height)
方法2:直接访问textBounds属性
Text实例完成布局后,会将边界信息存储在textBounds属性中,通过其中的坐标值计算宽高:
await myText.sync() const { left, right, top, bottom } = myText.textBounds const width = right - left const height = bottom - top console.log('文本宽度:', width) console.log('文本高度:', height)
方法3:使用Three.js原生边界框
由于troika的Text继承自Three.js的Object3D,也可以用原生的边界框方法计算,但需要先更新对象矩阵:
import * as THREE from 'three' await myText.sync() // 更新矩阵确保边界框计算准确 myText.updateMatrixWorld(true) const box = new THREE.Box3().setFromObject(myText) const width = box.max.x - box.min.x const height = box.max.y - box.min.y console.log('文本宽度:', width) console.log('文本高度:', height)
注意事项
- 必须等待
sync()完成:sync()是异步方法,返回Promise,需用await或then回调处理;若未手动调用sync(),troika会在帧渲染前自动完成,但此时直接获取属性可能得到旧值或空值。 - 属性变更后需重新同步:当文本内容、字体大小、字间距等属性修改后,必须重新调用
sync()才能获取最新的宽高值。
内容的提问来源于stack exchange,提问作者BAR
相关产品推荐
相关产品推荐

