vue页面中
<div ref="container"></div>
data声明
scene: null,
camera: null,
renderer: null,
controls: null,
rotationType: 'sphere',
rotationTimer: null,
backgroundImageUrl: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/plugin/cake/screen-bg.png',
sphereGroup: null,
defautNum: 200,
渲染方法
initThree() {
this.clearScene();
// 创建场景
this.scene = new THREE.Scene();
// 设置场景背景为透明
this.scene.background = null;
// 创建相机
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this.camera.position.z = 10;
// 创建渲染器
this.renderer = new THREE.WebGLRenderer({ alpha: true });
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setClearColor(0x000000, 0); // 设置清除颜色为透明
const canvas = this.renderer.domElement;
canvas.style.zIndex = 1; // 设置画布的 z-index
this.$refs.container.appendChild(canvas);
// 创建控制器
this.controls = new OrbitControls(this.camera, canvas);
// 创建一个用于存放球体元素的组
this.sphereGroup = new THREE.Group();
this.scene.add(this.sphereGroup);
},
animate() {
this.isAnimate = true;
requestAnimationFrame(this.animate);
if (this.rotationType === 'sphere') {
if (this.sphereGroup) {
this.sphereGroup.rotation.y += 0.01;
}
}
this.controls.update();
this.renderer.render(this.scene, this.camera);
},
createInitialSphere() {
const radius = 5;
if(this.signList.length > 0){
if (this.signList.length >= this.defautNum) {
// 超出200个截取组成
this.peopleList = this.signList.slice(0, this.defautNum);
} else {
// 未超出200个随机截取组成
for (let i = 0; i < this.defautNum; i++) {
const randomIndex = Math.floor(Math.random() * this.signList.length);
this.peopleList.push(this.signList[randomIndex]);
}
}
}else{
for (let i = 0; i < 200; i++) {
this.peopleList.push({
uid: null,
nickname: '默认用户',
avatar: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/liveCardBj.png'
});
}
}
for (let i = 0; i < this.defautNum; i++) {
const participant = this.peopleList[i];
const loader = new THREE.TextureLoader();
loader.load(participant.avatar, (texture) => {
const material = new THREE.MeshBasicMaterial({ map: texture });
const geometry = new THREE.PlaneGeometry(1, 1);
const mesh = new THREE.Mesh(geometry, material);
const group = new THREE.Group();
group.add(mesh);
participant.group = group;
const phi = Math.acos(-1 + (2 * i) / this.defautNum);
const theta = Math.sqrt(this.defautNum * Math.PI) * phi;
const x = radius * Math.cos(theta) * Math.sin(phi);
const y = radius * Math.sin(theta) * Math.sin(phi);
const z = radius * Math.cos(phi);
group.position.set(x, y, z);
group.lookAt(0, 0, 0);
this.sphereGroup.add(group);
});
}
},
渲染有一个问题 重新触发会导致球体运动加速;再这里要加个判断如果有触发动画的话;再次渲染不需要加载动画方法
that.initThree();
if (!that.isAnimate){
that.animate();
}
that.createInitialSphere();