用threejs实现掘金红包封面-3D旋转四角星(5)

472 阅读2分钟

「这是我参与2022首次更文挑战的第27天,活动详情查看:2022首次更文挑战

背景

本片文章是一个专栏的一篇,大家可以查看我的专栏,然后连起来一起浏览,上一篇文章(用threejs实现掘金红包封面-实现中文和SVG)我们实现了3D旋转星光,本篇文章我准备实现3D旋转四角星,接下来我就来一步一步的实现它吧!

image.png

技术

threejs知识点

  1. ConeGeometry
  2. MeshLambertMaterial
  3. Group

实现 3D旋转四角星

1. 创建一个角

因为四角星可以看做由四个锥形组和而成的,所以我们可以先画一个锥形。代码如下:

const geometry = new THREE.ConeGeometry(3, 6, 4);
const material = new THREE.MeshLambertMaterial({
color: 0xffcea3,
opacity: 0.7,
});
const mesh = new THREE.Mesh(geometry, material);

效果:

image.png

2. 创建四个角

由上一步我们可以创建四个锥形,组合成一个四角星。

for (let i = 0; i < 4; i++) {
      const geometry = new THREE.ConeGeometry(3, 6, 4);
      const material = new THREE.MeshLambertMaterial({
        color: 0xffcea3,
        opacity: 0.7,
      });
      const mesh = new THREE.Mesh(geometry, material);
      const cone = this.setPivot(0, -3, 0, mesh);
 }

3. 组合成一个四角星

const fourStarGroup = new THREE.Group();
    for (let i = 0; i < 4; i++) {
      const geometry = new THREE.ConeGeometry(3, 6, 4);
      const material = new THREE.MeshLambertMaterial({
        color: 0xffcea3,
        opacity: 0.7,
      });
      const mesh = new THREE.Mesh(geometry, material);
      const cone = this.setPivot(0, -3, 0, mesh);
      cone.rotateZ(Math.PI / 2);
      cone.rotateZ((Math.PI / 2) * i);
      fourStarGroup.add(cone);
 }

效果如下:

image.png

4. 创建两个四角星

setFourStar(): void {
    this.setFourStarLeft();
    this.setFourStarRight();
 }

5. 设置位置和大小

  • 左边的四角星:
setFourStarLeft(): void {
    this.fourStarLeftGroup = new THREE.Group();
    const fourStarLeftGroup = this.setFourStarGroup();
    this.fourStarLeftGroup.add(fourStarLeftGroup);
    this.fourStarLeftGroup.position.set(-25, 0, 0);
    this.fourStarLeftGroup.scale.set(0.8, 0.8, 0.8);
    this.scene && this.scene.add(this.fourStarLeftGroup);
}
  • 右边的四角星:
setFourStarRight(): void {
    this.fourStarRightGroup = new THREE.Group();
    const fourStarRightGroup = this.setFourStarGroup();
    this.fourStarRightGroup.add(fourStarRightGroup);
    this.fourStarRightGroup.position.set(25, 20, 0);
    this.scene && this.scene.add(this.fourStarRightGroup);
  }

效果如下:

6. 设置旋转动画

  • 左边的四角星动画:
if (this.fourStarLeftGroup) {
      const axis = new THREE.Vector3(0, 1, 0); //向量axis
      this.fourStarLeftGroup.rotateOnAxis(axis, -Math.PI / 200); //绕axis轴旋转π/8
    }
  • 右边的四角星动画:
if (this.fourStarRightGroup) {
      const axis = new THREE.Vector3(0, 1, 0); //向量axis
      this.fourStarRightGroup.rotateOnAxis(axis, -Math.PI / 200); //绕axis轴旋转π/8
    }

本文效果展示

动画1.gif

整体效果

结合上几篇文章的旋转文字环,整体效果如下: 动画.gif

总结

在整体效果上已经完成了80%了红包封面了,但是在细节上还是有很多不足的地方,比如threejs 加载文字慢,掘金的logo角度和颜色细节还是不太像,因为本人不知道掘金logo的具体色号,所以在细节上还是有很多不足的,不过也希望大家多多点赞和提意见,这样我才有动力努力创作,最后谢谢大家的观看!!!

相关文章

用threejs实现掘金红包封面-3D旋转星光