安裝
npm install three
在Vue中引入import * as THREE from 'three
- Three.js應用三要素
- Camera:攝像機,分為透視相機(PerspectiveCamera)和正投影(OrthographCamera)
- PerspectiveCamera(fov, aspect, near, far)
- OrthographCamera(left, right, top, bottom, near far)
- position<x, y, z>: 攝像機位置
- up<x, y, z>: 上方向(旋轉角度)
- lookAt(<x, y, z>): 相機朝向
- Secne:場景
- Renderer:渲染器
- Camera:攝像機,分為透視相機(PerspectiveCamera)和正投影(OrthographCamera)
<template>
<div id="app" ref="container">
</div>
</template>
<script>
import * as THREE from 'three'
export default {
name: 'App',
data () {
return {
scene: null,
camera: null,
geometry: null,
material: null,
mesh: null,
renderer: null
}
},
mounted() {
this.camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
this.camera.position.z = 1;
this.scene = new THREE.Scene();
this.geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
this.material = new THREE.MeshNormalMaterial();
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.scene.add( this.mesh );
this.renderer = new THREE.WebGLRenderer( { antialias: true } );
this.renderer.setSize( window.innerWidth, window.innerHeight );
// this.renderer.clearColor("#FFFFFF");
this.$refs.container.appendChild(this.renderer.domElement);
this.animate();
},
methods: {
animate() {
requestAnimationFrame( this.animate );
this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.02;
this.renderer.render( this.scene, this.camera );
}
}
}
</script>
<style>
html body{
padding: 0;
margin: 0;
overflow: hidden;
}
#app {
padding: 0;
margin: 0;
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
overflow: hidden;
}
</style>
執行結果
- 環境光:物體的每個面都受到相同角度和強弱程度的光源照射
let light = new THREE.AmbientLight(0xFFFFFF, 1.0); scene.add(light)
- 方向光:光的位置會影響照射角度,但不會改變照射強度
let light = new THREE.DirectionalLight(0xFFFFFF, 1.0); light.position.set(options.x, options.y, options.z); scene.add(light)
- 點光源:具有照射距離和衰減屬性,燈光強度會在指定距離內衰減指定強度,並且其位置會影響照射物體的角度和強弱
let light = new THREE.PointLight(0xFFFFFF, 1.0, 100, 0.1); light.position.set(options.x, options.y, options.z); scene.add(light);
載入紋理圖片
let loader = new THREE.TextureLoader(); let texture = loader.load("image url", // 載入成功回撥函式 texture => { }, // 載入時回撥函式 xhr => { }, // 載入錯誤回撥函式 err => { }); let material = new THREE.MeshBasicMaterial({map: texture});
紋理重複方式
// 垂直方向上將如何包裹 texture.wrapT // 水平方向上將如何包裹 texture.wrapS // 下次使用紋理時是否觸發一次更新 needsUpdate=true/false // 簡單重複 THREE.RepeatWrapping // 邊緣拉伸 THREE.ClampToEdgeWrapping // 映象重複 THREE.MirroredRepeatWrapping
本作品採用《CC 協議》,轉載必須註明作者和本文連結