Three.js学习笔记(1)

前言

由于近期的一些业务需要用到一些webgl的东西,three.js可以说是webgl相关库里最完善的,所以毫无疑问的开始了three.js入坑之旅

搭建开发环境

由于webpack搭建环境太过麻烦(懒),所以这里选择了parcel来进行打包,主要包括一个入口的index.html文件和一个index.js文件。同时在这个目录下运行yarn add three
index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>threejs</title>
    <style>
      body {
        margin: 0;
        overflow: hidden;
      }
    </style>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script src="./index.js"></script>
  </body>
</html>

index.js

import * as THREE from 'three'
window.THREE = THREE
// init scene
const scene = new THREE.Scene()

// init camera
const camera = new THREE.PerspectiveCamera(
  45,
  window.innerWidth / window.innerHeight,
  0.1,
  1000000
)
camera.position.z = 5

// init renderer
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setClearColor(0xeeeeee)
document.body.appendChild(renderer.domElement)

// init light
const light = new THREE.AmbientLight(0xffffff, 2)
scene.add(light)

// init controls
require('three/examples/js/controls/OrbitControls')
const controls = new THREE.OrbitControls(camera, renderer.domElement)

// init object
const geometry = new THREE.BoxGeometry(2, 2, 2)
const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00
})
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)

// handle window resize
window.addEventListener('resize', () => {
  renderer.setSize(window.innerWidth, window.innerHeight)
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
})

function animate() {
  requestAnimationFrame(animate)
  renderer.render(scene, camera)
  controls.update()
}

animate()

运行代码

cd到上面那两个文件的同级目录下,运行parcel index.html,parcel会在1234端口启动开发服务,并且在代码修改后会自动刷新。
当parcel显示打包完成后,打开localhost:1234就可以看到一个绿色的正方体在屏幕中央了
一个简单的demo就这样运行起来了,接下来我们就可以基于这个模板去探究three.js更深层的东西了~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容