1.下包引入
//下包
npm install three
yarn add three//引入
import * as THREE from 'three'
2.创建场景,摄像机
// 1.创建场景const scene = new THREE.Scene()// 2.创建摄像机//第一个参数是视角,一般在60-90之间,第二个参数是场景的尺寸,一般取显示器的宽高,第三个参数是开始位置,第四个参数是结束位置const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)// 设置摄像机z轴的空间的位置camera.position.z = 3
3.创建渲染器
// 3.创建渲染器const renderer = new THREE.WebGLRenderer()// 设置渲染器场景的大小renderer.setSize(window.innerWidth, window.innerHeight)// 把渲染器添加到页面中去document.body.appendChild(renderer.domElement)
4.创建几何模型,网格对象
这样创建的几何模型是纯色的方块,效果如上图
// 4.创建几何模型const box = new THREE.BoxGeometry(1, 1, 1)// 设置几何体的材质(纯色)const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })// 创建网格对象const cube = new THREE.Mesh(box, material)// 将网格对象添加到场景中去scene.add(cube)
添加贴图(皮肤)
import logo from '@/assets/dz.png'// 4.创建几何模型const box = new THREE.BoxGeometry(1, 1, 1)// 设置几何体皮肤(贴图)const texture = new THREE.TextureLoader().load(logo)const material = new THREE.MeshBasicMaterial({ map: texture })// 创建网格对象const cube = new THREE.Mesh(box, material)// 将网格对象添加到场景中去scene.add(cube)
5.场景渲染
这一步将前面的设置全部加入到画布中
// 5.场景渲染function animate () {requestAnimationFrame(animate)// 给网格对象添加动画cube.rotation.x += 0.01cube.rotation.y += 0.01renderer.render(scene, camera)}animate()
6.响应式布局
拖动网页,刷新后画布尺寸发生变化,再次拖动窗口,会出现空白
window.addEventListener('resize', () => {// 初始化相机camera.aspect = window.innerWidth / window.innerHeightcamera.updateProjectionMatrix()renderer.setSize(window.innerWidth, window.innerHeight)})
7.完整代码
<template><div class="container"></div>
</template>
<script>
import * as THREE from 'three'
import logo from '@/assets/dz.png'
export default {data () {return {}},mounted () {this.init()},methods: {init () {// 1.创建场景const scene = new THREE.Scene()// 2.创建摄像机const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)// 设置摄像机z轴的空间的位置camera.position.z = 4// 3.创建渲染器const renderer = new THREE.WebGLRenderer()// 设置渲染器场景的大小renderer.setSize(window.innerWidth, window.innerHeight)// 把渲染器添加到页面中去document.querySelector('.body').appendChild(renderer.domElement)// document.body.appendChild(renderer.domElement)// 4.创建几何模型const box = new THREE.BoxGeometry(1, 1, 1)// 设置几何体皮肤(贴图)const texture = new THREE.TextureLoader().load(logo)const material = new THREE.MeshBasicMaterial({ map: texture })// 设置几何体的材质(纯色)// const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })// 创建网格对象const cube = new THREE.Mesh(box, material)// 将网格对象添加到场景中去scene.add(cube)// 5.场景渲染function animate () {requestAnimationFrame(animate)// 给网格对象添加动画cube.rotation.x += 0.01cube.rotation.y += 0.01renderer.render(scene, camera)}animate()// 响应式布局window.addEventListener('resize', () => {// 初始化相机camera.aspect = window.innerWidth / window.innerHeightcamera.updateProjectionMatrix()renderer.setSize(window.innerWidth, window.innerHeight)})}}
}
</script>
<style lang='scss' scoped></style>