vue中使用three绘制星空效果

2 篇文章 0 订阅


关于使用three绘制星空效果的记录


一、Three.js 是什么?

Three.js 是一款运行在浏览器中的 3D 引擎,你可以用它创建各种三维场景,包括了摄影机、光影、材质等各种对象。

二、使用步骤

1.引入库

首先npm install three

import * as THREE from "three";

2.开始绘制星空

data中定义变量

  data() {
    return {
      camera: null,
      scene: null,
      starsGeometry: null,
      starField:null,
      renderer: null,
    }
  },

创建相机渲染器等

    inti(){
      this.camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
      this.camera.position.z = 1400;
      this.scene = new THREE.Scene();
      this.starInti()
      this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true,});
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      // this.renderer.domElement.style.position = 'absolute';
      document.getElementById('threeStar').appendChild(this.renderer.domElement);
    },

生成星空

starInti() {
      //星空
      this.starsGeometry = new THREE.Geometry();
      //生成点的位置
      for (var i = 0; i < 12000; i++) {
        var star = new THREE.Vector3();
        //THREE.Math.randFloatSpread 在区间内随机浮动* - 范围 / 2 *到* 范围 / 2 *内随机取值。
        star.x = THREE.Math.randFloatSpread(2000);
        star.y = THREE.Math.randFloatSpread(2000);
        star.z = THREE.Math.randFloatSpread(2000);
        this.starsGeometry.vertices.push(star);
      }
      var starsMaterial = new THREE.PointsMaterial({ color: '#fff',sizeAttenuation: false });
      this.starField = new THREE.Points(this.starsGeometry, starsMaterial);
      this.scene.add(this.starField);
    },

定义动画

    animate() {
      requestAnimationFrame(this.animate);

      //星空旋转可通过镜头旋转或者物体旋转实现
        // this.camera.rotation.y = this.camera.rotation.y -0.0005 //镜头旋转
      this.starField.rotation.y+=0.0002
      this.starField.rotation.x+=0.0002
      this.starField.rotation.z+=0.0002
      this.render();
    },

渲染

render() {
      this.renderer.render(this.scene, this.camera);
    },

在mounted中调用方法

  mounted() {
    this.inti()
    this.animate()
    this.render()
  },

div

<template>
  <div id="threeStar" ref="threeStar"></div>
</template>

样式

<style lang="scss" scoped>
#threeStar {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: 9;
  //bottom: 4vh;
}
</style>

在这里插入图片描述


总结

以上就是使用threejs绘制简单星空效果,在要应用的vue页面引入该组件即可。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值