新手上路-第一步,引入three.js,去Three.js – JavaScript 3D Library
.html文件引入three.js引擎
相对地址加载
(three.js官网 通过地址保存到本地 https://threejs.org/build/three.js)
<script src="js/three.js"></script>
或者github下载特定版本
https://github.com/mrdoob/three.js
使用http绝对地址加载
https://cdn.bootcss.com/three.js/92/three.js
或者
http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js
npm引入three.js引擎
npm install three
// Option 1: 引入整个three.js代码依赖库
import * as THREE from 'three';
const scene = new THREE.Scene();
// Option 2: 引入需要的部分
import { Scene } from 'three';
const scene = new Scene();
npm 安装特定版本 npm install three@0.111.0 --save (安装111版本)
一个完整的代码需要:基础三件套【场景 - 相机 - 渲染器】
(render the scene with camera)
(图片来自 Three.js零基础入门教程 WebGL)
首先创建三件套,通用属性如下;再创建物体(如简单的立方体),最后进入渲染
(如果不渲染无法看到任何东西,为此,需要一个所谓的渲染或动画循环)
完整代码:(来自 three.js docs)
(代码中的 引入的three.js 来自图1)
renderer.domElement可以访问three.js渲染的结果,也就是HTML元素的canvas布局
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script>
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.domElement可以访问three.js渲染的结果,也就是HTML元素的canvas布局
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 );
};
animate();
</script>
</body>
</html>
通用属性 相机:PerspectiveCamera 渲染器:WebGLRenderer 场景 • 物体(立方体):BoxGeometry • 材质:MeshBasicMaterial • 贴图:Mesh
注意事项:
1.默认情况下,当我们添加场景时,使用scene.add(),
==我们添加的东西将被放到到坐标(0、0、0)中,如camera和cube, 为了避免这种情况,通常移动相机位置==
2.如果不渲染无法看到任何东西,为此,我们需要一个所谓的渲染或动画循环(强大的渲染功能)
html5 还提供一个专门用于请求动画的API → requestAnimationFrame
window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行,回调间隔时间通常为每秒60次;且运行在后台标签页或者隐藏的<iframe> 里时,requestAnimationFrame() 会被暂停调用以提升性能和电池寿命。(来自MDN)