me icon indicating copy to clipboard operation
me copied to clipboard

学习 three.js (Part 1: hello world)

Open nonocast opened this issue 5 months ago • 0 comments

ref: Installation – three.js docs

操作步骤略有不同:

  1. yarn create vite, project: hello, framework选择Vanilla
  2. code打开hello, 在terminal中运行yarn安装依赖,然后yarn dev运行,打开可以看到vite默认页面
  3. yarn add three
  4. 然后copy three.js docs中index.html代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>My first three.js app</title>
  <style>
    body {
      margin: 0;
    }
  </style>
</head>

<body>
  <script type="module" src="/main.js"></script>
</body>

</html>
  1. copy main.js代码
import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animate );
document.body.appendChild( renderer.domElement );

const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;

function animate() {
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render( scene, camera );
}

打开浏览器看到green cube, 收工。

cube

注:

  • vite代替了create-react-app
  • 不建议使用script tag引用script,几次都失败

参考阅读:

nonocast avatar Sep 04 '24 16:09 nonocast