在前一篇文章(Threejs入门-安装教程-CSDN博客)中,我们介绍了threejs官方的安装流程,对于同学们学习中比较繁琐复杂,本文介绍在实际学习中使用的方法。
1、安装开发中需要的js库。
win+R输入cmd进入控制台,命令进入学习中的项目文件夹。
npm命令安装threejs,npm i three,该方法会安装最新的threejs。
项目文件夹会多出以下文件内容:
2、使用vscode打开这个工作文件夹。
在开发中需要使用的js库都在以下文件中。仍然需要拓展插件five serves(GitHub - yandeu/five-server: ⚡ Development Server with Live Reload Capability. (Maintained Fork of Live Server))可以在vscode插件市场直接下载。
新建一个index.html网页文件。
将html与js代码写在一个文件中。
这是需要注意的注意点:
这段代码对应这一句代码 import * as THREE from 'three';
<script type="importmap">
{
"imports":{
"three":"./node_modules/three/build/three.module.js"
}
}
</script>
(注意逗号,后面没有多余的路径项,就把逗号去掉)
如果不清楚路径怎么寻找的同学,可以去学习文件路径的知识。
3、代码+结果。
结合官方中,需要对浏览器的兼容性检测,加入一些代码。
<!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中的import的简短路径
注意每个路径之间的逗号,最后不加逗号 -->
<script type="importmap">
{
"imports":{
"three":"./node_modules/three/build/three.module.js",
"three/addons/": "./node_modules/three/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';
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() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
if (WebGL.isWebGLAvailable()) {
// Initiate function or other initializations here
animate();
} else {
const warning = WebGL.getWebGLErrorMessage();
document.getElementById('container').appendChild(warning);
}
</script>
</body>
</html>
这时就可以实现在一个项目文件夹下建立多个网页了,不需要安装多个构建工具。