赞
踩
关于使用three绘制星空效果的记录
Three.js 是一款运行在浏览器中的 3D 引擎,你可以用它创建各种三维场景,包括了摄影机、光影、材质等各种对象。
首先npm install three
import * as THREE from "three";
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页面引入该组件即可。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。