index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入three.js -->
<!-- <script src="./build/three.js"> -->
</script>
</head>
<body>
<div id="webgl" style="margin-top: 100px;margin-left:200px;"></div>
<!-- 实际开发环境中需要先配置路径 -->
<script type="importmap">
{
"imports": {
"three": "./build/three.module.js",
"three/addons/": "../three.js/examples/jsm/"
}
}
</script>
<script type="module" src="./index.js">
</script>
</body>
</html>
index.js
// 按ES6方式的引入threejs
import * as THREE from 'three'
//创建一个三维场景scene
const scene = new THREE.Scene()
//给三维场景添加物体
// 定义一个长方体,长宽高都为100
const geometry = new THREE.BoxGeometry(50, 50, 50)
//定义一个基础网格材质
const material = new THREE.MeshBasicMaterial({
color: 0x00ffff,//红色材质
transparent: true,//开启透明
opacity: 0.5,//设置透明度
})
//创建一个网格模型:表示生活中的物体
const mesh = new THREE.Mesh(geometry, material)
//设置网格模型(物体)在三维空间中的位置坐标,默认是坐标原点
mesh.position.set(0, 70, 0)
//通过.add方法=>把mesh添加到三维场景中
scene.add(mesh)
// console.log('mesh', mesh)
//创建一个三位坐标轴
// AxesHelper:辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(150);
// 将坐标轴对象添加到三维场景中
scene.add(axesHelper);
//定义相机输出画布的canvas尺寸
const width = 800;
const height = 500;
//设置相机的四个参数
//创建一个透视投影相机对象
const camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 2000);
//设置相机位置
camera.position.set(200, 200, 200)
//相机的视线 观察目标点的坐标
camera.lookAt(0, 0, 0);//坐标原点
// camera.lookAt(0, 10, 0);//y轴上一点
// camera.lookAt(mesh.position);//指向网格模型
//创建一个WebGL渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(width, height);//canvas画布宽高度
renderer.render(scene, camera);//渲染场景和相机,类比相机的拍照动作
//把渲染结果canvas画布,也就是照片渲染到前端页面上
// document.body.appendChild(renderer.domElement)
document.getElementById('webgl').appendChild(renderer.domElement)