安装
npm install three --save
使用
页面直接引入import * as THREE from 'three'
<template>
<div>
<div id="container"></div>
</div>
</template>
<script>
import * as Three from 'three'
import {
OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
export default {
name: 'ThreeTest',
data() {
return {
camera: null,
scene: null,
renderer: null,
mesh: null
}
},
methods: {
init() {
let container = document.getElementById('container');
// 创建场景
this.scene = new Three.Scene();
/**
* 透视投影相机设置
*/
//设置相机
this.camera = new Three.PerspectiveCamera(60, container.clientWidth / container.clientHeight, 1, 1000);
// this.camera.position.z = 1;
this.camera.position.set(1, 1, 1);
// 正投影相机设置
// const width = window.innerWidth; //窗口宽度
// const height = window.innerHeight; //窗口高度
// const k = width / height; //窗口宽高比
// const s = 1; //三维场景显示范围控制系数,系数越大,显示的范围越大
// //创建相机对象
// this.camera = new Three.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
// this.camera.position.set(200, 300, 200);
//长方体 参数:长,宽,高
let geometry = new Three.BoxGeometry(0.2, 0.2, 0.2);
//材质设置
// let material = new Three.MeshNormalMaterial();
//给物体上色
var material = new Three.MeshBasicMaterial({
color:0x000099})
this.mesh = new Three.Mesh(geometry, material);
//将图形添加到场景中
this.scene.add(this.mesh);
// 创建渲染器
this.renderer = new Three.WebGLRenderer({
antialias: true });
// 设置渲染器初始颜色
this.renderer.setClearColor(new Three.Color('#666'))
//设置输出canvas画面大小
this.renderer.setSize(container.clientWidth, container.clientHeight);
// // 显示三维坐标
// var axes = new THREE.AxesHelper(20)
// // 添加坐标系到场景中
// this.scene.add(axes)
//将渲染器输出添加html元素中
container.appendChild(this.renderer.domElement);
},
animate() {
requestAnimationFrame(this.animate);
//自动旋转
// this.mesh.rotation.x += 0.01;
// this.mesh.rotation.y += 0.02;
this.renderer.render(this.scene, this.camera);
},
// 创建控件对象
createControls() {
this.controls = new OrbitControls(this.camera, this.renderer.domElement)
}
},
mounted() {
this.init();
this.animate()
this.createControls()
}
}
</script>
<style scoped>
#container {
height: 100%;
}
</style>