vue 中使用three.js

vue

1.使用vue-cli工具创建一个vue项目

vue create projectName

2.安装three.js" title="three.js">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>

以上是 vue 中使用three.js 的全部内容, 来源链接: utcz.com/z/379804.html

回到顶部