vue 中使用three.js
1.使用vue-cli工具创建一个vue项目
vue create projectName
2.安装three.js
npm install three -S
3.创建index.vue页面
在该页面中导入THREE: import * as THREE from 'three'
<template>
<div class="app-wrap" ref="view">
</div>
</template>
<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' // 控制器
let scene, camera, renderer, controler;//将场景等变量定义在全局,尽量不要挂载到vue实例上
export default {
data () {
return {
viewNode: null,
animationId: null
}
},
methods:{
//three场景初始化
initThreeScene() {
this.viewNode = this.$refs.view;
scene = new THREE.Scene()
camera = new THREE.PerspectiveCamera( 45, this.viewNode.clientWidth / this.viewNode.clientHeight, 1, 18000 );
camera.position.set(0, 50, 20)
renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize( this.viewNode.clientWidth , this.viewNode.clientHeight );
this.viewNode.appendChild( renderer.domElement );
let AmbientLight = new THREE.AmbientLight( 0xcccccc);
scene.add( AmbientLight )
var DirectionalLight = new THREE.DirectionalLight( 0xeeeeee)
DirectionalLight.position.set( 0, 150, 0 );
scene.add( DirectionalLight );
//控制器,旋转缩放场景等
controler = new OrbitControls(camera, renderer.domElement);
controler.minPolarAngle = 0;
controler.maxPolarAngle = Math.PI/2;
controler.minDistance = 1;
controler.maxDistance = 800;
//辅助线
let grid = new THREE.GridHelper( 50, 30, 0xcc4400, 0x404543 );
scene.add( grid );
},
animation() {
renderer.render(scene,camera)
this.animationId = requestAnimationFrame(this.animation);
}
},
mounted(){
this.initThreeScene();
this.animation();
},
//页面销毁时记得销毁场景防止内存泄漏
destroyed() {
scene.clear()
renderer.dispose()
renderer.forceContextLoss()
renderer.content= null
cancelAnimationFrame(this.animationId)
}
}
</script>
<style scoped>
.app-wrap {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
</style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了