Three.js(13)——3D text(二)

241 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第14天,点击查看活动详情 >>

今天,我们来继续实现下面这种效果,实现远近大小不同的甜甜圈围绕在文字周围的效果:

微信截图_20220819152549.png

文字

让文字居中

没有设置之前,文字都不是根据整个画布垂直水平居中对齐的,而是整个文字的左下角位于画布的中心点。想要文字根据画布垂直水平居中有两种方法:

.center()方法

可以根据边界矩形将几何体居中。

// 写法1:
textGeometry.translate(
    -(textGeometry.boundingBox.max.x  - 0.02) * 0.5,
    -(textGeometry.boundingBox.max.y  - 0.02) * 0.5,
    -(textGeometry.boundingBox.max.z  - 0.02) * 0.5,
);
// 写法2:
textGeometry.center();

引用字体

文本几何体使用 typeface.json 所生成的字体。一些已有的字体可以在/examples/fonts中找到,且必须在页面中引入。如:

import typefaceFont from "three/examples/fonts/helvetiker_regular.typeface.json";

给文字旁边添加随机大小随机位置的甜甜圈

// 甜甜圈的几何体与材质:放到外面不用循环多次,节省时间,优化性能
const donutGeometry = new THREE.TorusBufferGeometry(0.3, 0.2, 20, 45);
const donutMetarial = new THREE.MeshMatcapMaterial({
    matcap: matcapTexture,
});
// 做200个甜甜圈
for (let i = 0; i < 200; i++) {
    const donut = new THREE.Mesh(donutGeometry, donutMetarial);
    
    // 让甜甜圈们的位置随机
    donut.position.x = (Math.random() - 0.5) * 10;
    donut.position.y = (Math.random() - 0.5) * 10;
    donut.position.z = (Math.random() - 0.5) * 10;

    // 让甜甜圈的角度随机
    donut.rotation.x = Math.random() * Math.PI;
    donut.rotation.y = Math.random() * Math.PI;

    // 让甜甜圈的大小随机
    const scale = Math.random();
    // 简单写法:
    donut.scale.set(scale, scale, scale);
    // 一般写法:
    /* donut.scale.x = scale;
    donut.scale.y = scale;
    donut.scale.z = scale; */

    scene.add(donut);
}

圆环缓冲几何体(TorusGeometry)

一个用于生成圆环几何体的类。

代码示例

const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const torus = new THREE.Mesh( geometry, material );
scene.add( torus );