vue多个three.js场景
时间: 2024-12-11 22:14:08 浏览: 7
在Vue中使用多个three.js场景可以通过以下步骤实现:
1. **安装three.js**:
首先,确保你已经安装了three.js。你可以使用npm来安装:
```bash
npm install three
```
2. **创建Vue组件**:
创建一个Vue组件,并在其中初始化多个three.js场景。
```vue
<template>
<div>
<div ref="container1" style="width: 500px; height: 500px;"></div>
<div ref="container2" style="width: 500px; height: 500px;"></div>
</div>
</template>
<script>
import * as THREE from 'three';
export default {
name: 'MultipleScenes',
mounted() {
this.initScene1();
this.initScene2();
},
methods: {
initScene1() {
const container = this.$refs.container1;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
},
initScene2() {
const container = this.$refs.container2;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(renderer.domElement);
const geometry = new THREE.SphereGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x0000ff });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
}
}
};
</script>
<style scoped>
div {
display: inline-block;
}
</style>
```
在这个示例中,我们创建了两个three.js场景,每个场景都有自己的渲染器、场景、相机和几何体。我们使用`ref`属性来引用HTML容器,并在其中初始化three.js场景。
阅读全文