上代码
three.js 源码 copy https://threejs.org/build/three.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>My first three.js app</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<script src="../public/three.js"></script>
<script>
// 参考 https://threejs.org/docs/index.html#manual/zh/introduction/Creating-a-scene
// Our Javascript will go here.
const scene = new THREE.Scene()
// PerspectiveCamera 透视摄像机
// 参数:视野角度(FOV),长宽比(aspect ratio),近截面(near)和远截面(far)只能看到两个值之间的物体
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000,
)
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
// 添加一个立方体
const geometry = new THREE.BoxGeometry(1, 1, 1) // 立方体,可设置 顶点(vertices)和面(faces)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }) // 材质
const cube = new THREE.Mesh(geometry, material) // Mesh(网格)
scene.add(cube) // 被添加到(0,0,0)坐标,摄像机和物体重合
camera.position.z = 5 // 相机向外移点
// 需要 “渲染循环”(render loop)或者“动画循环”(animate loop)
// 屏幕刷新率一般是60次/秒,因此 创建了一个使渲染器 能够在每次屏幕刷新时 对场景进行绘制的循环
// why not setInterval? 因为 requestAnimationFrame 当用户切换到其它的标签页时,它会暂停,因此不会浪费用户宝贵的处理器资源,也不会损耗电池的使用寿命。
function animate() {
requestAnimationFrame(animate)
// let's dance!
cube.rotation.x += 0.01
cube.rotation.y += 0.01
renderer.render(scene, camera)
}
animate()
</script>
</body>
</html>