本篇文章是对于第一次接触threejs并且对官方安装文档看不懂以及操作不熟的同学,本文提供有需要的帮助!
1、官方网站
1、点击进入官网:Three.js – JavaScript 3D Library
以下文件可以下载,也可以不下载,根据需求来决定,里面有许多的实例。
点击code下面的download和github,可以选择在github(https://github.com/mrdoob/three.js/)上下载源代码。可以使用某雷加速下载。
下载的例子不能直接使用浏览器运行,需要借助编程工具vscode(Visual Studio Code - Code Editing. Redefined)。使用vscode查看例子,另外需要安装拓展插件:five serves
2、官方文档
1、找到官方文档,切换成中文。
3、安装过程
1、方案一:使用 NPM 和构建工具进行安装
1、安装node.js(Node.js),下载第一个稳定版本。
2、win+R,输入cmd打开控制台。进入项目文件夹中。输入npm install --save three,安装three.js文件
在文件夹中多出以下文件:
3、在相同目录下安装vite构建工具。代码:npm install --save-dev vite。
确保以上文件安装成功。使用npx vite来检查以上工具是否安装成功。此时复制Local地址到浏览器中查看连接情况。
4、在下面的相同目录中,建立index.html和main.js两个文件。
5、输入代码:
<!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>
在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);
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);
cube.position.x += 4;
scene.add(cube);
const cube2 = new THREE.Mesh(geometry, material);
scene.add(cube2);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
运行结果:
2、方案二:从 CDN 导入
注:使用此方法不稳定,如果你的网络不能连接到https://unpkg.com/[email protected]/build/three.module.js,https://unpkg.com/[email protected]/examples/jsm/这两个网站时,浏览器不会显示任何内容,相当于在线平台。方案一的相当于离线平台。
1、node.js需要安装,同上。
2、需要在项目文件夹中安装serve。使用安装:npm i serve。
不需要下载vite工具。也不需要下载three.js文件。
在index.html中的代码略作修改。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body {
margin: 0;
}
</style>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/[email protected]/build/three.module.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
}
}
</script>
</head>
<body>
<script type="module" src="main.js"></script>
</body>
</html>
运行效果:
自己通过threejs的官方文档总结的实操经验,有需要的可以点点赞!!!