试了很多次,终于找到一个可以正确在vue中使用three.js的方法。我觉得主要的问题是出在vue的版本上。
我刚开始尝试用过vue init webpack ***的方式创建vue项目,但是创建完的项目一加入three运行就报错,所有我改用vue create ** 创建项目。我刚开始创建项目选择的是vue3,创建完的项目加入three运行不报错但是引用three的其他组件又报错,所以改选择vue2。选择vue2发现在创建vue项目的时候就报错,最后找到报错的原因,是由于我npm的版本过高,降低npm的版本就好了。
步骤如下
1、npm的版本过高,先降低npm的版本。
npm install npm@6.14.10 -g
2、创建项目,选择vue2,其他选择看个人喜好
vue create demo
3、进入项目文件夹,添加three到项目中
npm install --save three
4、可以正常的书学代码,例子:
<template>
<div>
<div id="container"></div>
</div>
</template>
<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
export default {
name: 'City',
data () {
return {
camera:null,
scene:null,
renderer: null,
width:'',
height:'',
}
},
methods: {
init() {
this.initThree();
this.initScene();
this.initCamera();
this.initPlant();
//添加坐标轴
var axesHelper = new THREE.AxesHelper;
this.scene.add(axesHelper);
},
initThree:function(){
let container = document.getElementById('container');
this.width=container.clientWidth;
this.height=container.clientHeight;
this.renderer = new THREE.WebGLRenderer({antialias: true})
this.renderer.setSize(this.width, this.height)
container.appendChild(this.renderer.domElement)
},
initScene:function(){
this.scene = new THREE.Scene();
this.scene.add(new THREE.AmbientLight(0x3c3c3c));//环境光
},
initCamera:function(){
this.camera = new THREE.PerspectiveCamera(45,this.width / this.height,0.25, 1000);
this.camera.position.set( -12.69085400727962, 120.82969958208948, -69.97533778224751);
},
//插入地板
initPlant:function(){
var geometry1 = new THREE.BoxGeometry(80, 1, 80);
var matarial1 = new THREE.MeshPhongMaterial( {
color: '#ffffff'
// map: THREE.ImageUtils.loadTexture('img/3d66Model-593580-files-10.jpg') ,
// emissive:'blue',
} );
var cube = new THREE.Mesh(geometry1, matarial1);
cube.position.set(20,0,10);
this.scene.add(cube);
},
animate: function () {
//镜头移动
var controls = new OrbitControls(this.camera,this.renderer.domElement);
controls.target.set(0,-0.2,-0.2);
controls.update();
requestAnimationFrame(this.animate)
this.renderer.render(this.scene, this.camera);
}
},
mounted () {
this.init()
this.animate()
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#container {
height:500px;
}
</style>