创建项目
注意nodejs版本 18+,20+ ,版本管理工具juejin.cn/post/736497…
pnpm create vite
cd vite-threejs-demo
pnpm install
pnpm run dev
安装完在main.ts可能会有报错
需要安装插件,然后就没有了 marketplace.visualstudio.com/items?itemN…
创建一个场景
pnpm install --save three
为了真正能够让你的场景借助 three.js 来进行显示,我们需要以下几个对象:场景(scene)、相机(camera)和渲染器(renderer),这样我们就能透过摄像机渲染出场景。
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 );
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;
渲染场景
不会在页面中看到任何东西。这是因为我们还没有对它进行真正的渲染。为此,我们需要使用一个被叫做“渲染循环”(render loop)或者“动画循环”(animate loop)的东西。
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();
在这里我们创建了一个使渲染器能够在每次屏幕刷新时对场景进行绘制的循环
使立方体动起来
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
完整代码
<script setup lang="ts">
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);
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;
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
<template></template>
<style scoped></style>