3D开发初体验,入门教程
效果图:
结合VUE的实现代码:
<template>
<view class="">
<view id="aaa" ref="webglContainer"></view>
</view>
</template>
<script>
import * as THREE from 'three';
// 引入扩展库OrbitControls.js 相机控件对象,本质上是通过控件改变相机的位置
import {
OrbitControls
} from 'three/examples/jsm/controls/OrbitControls.js';
export default {
data() {
return {
title: 'Hello'
}
},
mounted() {
window.THREE = THREE;
// 创建场景
const scene = new THREE.Scene();
// 创建立方体
const geometry = new THREE.BoxGeometry(100, 100, 100);
// 材质 #aaaaff
const material = new THREE.MeshLambertMaterial({
color: 0xaaaaff,
transparent: true,
opacity: 0.9
});
//网格模型-表示物体(颜色,外观)
const mesh = new THREE.Mesh(geometry, material);
//设置网格模型的位置
// mesh.position.set(10,10,0)
//把网格模型添加到场景中
scene.add(mesh);
// 创建三维坐标轴
const axesHelper = new THREE.AxesHelper(150)
scene.add(axesHelper);
// 创建点光源
const pointLight = new THREE.PointLight(0xffffff, 1, 0, 0);
//设置光的位置
pointLight.position.set(180, 120, 100);
// 不管是光还是物体都需要添加到场景里,
scene.add(pointLight);
// 创建环境光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4); // 柔和的白光
scene.add(ambientLight);
// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
// camera.lookAt(0,0,0)//坐标原点 X,y,Z
camera.lookAt(mesh.position) //相机对准物体
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('aaa').appendChild(renderer.domElement);
// this.$nextTick(() => {
// const webglContainer = this.$refs.webglContainer;
// console.log('webglContainer', webglContainer);
// if (webglContainer instanceof HTMLElement) {
// webglContainer.appendChild(renderer.domElement);
// } else {
// console.error("webglContainer is not a valid DOM element2.");
// }
// });
//创建相机控件对象,本质上是通过控件改变相机的位置
const controls = new OrbitControls(camera, renderer.domElement)
controls.addEventListener("change", function() {
renderer.render(scene, camera)
})
function animate() {
requestAnimationFrame(animate);
// mesh.rotation.x += 0.01;
// mesh.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
},
methods: {
}
}
</script>
<style>
.webgl {}
</style>