说到3D,想必大家都能想到three.js,它是由WebGL封装出来的,接下来,我手把手教大家创建一个简单的3D页面
话尽在代码中,哈哈
大家可以复制代码玩一下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
</body>
<script type="module">
import * as THREE from 'https://unpkg.com/three/build/three.module.js'
// 创建场景
const scene = new THREE.Scene()
// 创建相机
const camera = new THREE.PerspectiveCamera()
// 调整相机
camera.position.z = 10
camera.position.y = 2
// 创建立方体
const geometry = new THREE.BoxGeometry()
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
// 网格
const cube = new THREE.Mesh(geometry, material)
cube.position.set(0, 3, 0)
scene.add(cube)
// 创建渲染器
const renderer = new THREE.WebGLRenderer()
// 调整渲染器大小
renderer.setSize(window.innerWidth, window.innerHeight)
// renderer中有domElement 是 canvas
document.body.appendChild(renderer.domElement)
// 添加网格地面
const gridHelper = new THREE.GridHelper(10, 10)
scene.add(gridHelper)
// 让立方体转起来
function animate() {
requestAnimationFrame(animate)
cube.rotation.x += 0.01
// 进行渲染
renderer.render(scene, camera)
}
animate()
</script>
</html>
效果图:
学海无涯,一起加油!