以下代码 示例了threejs的移动动画、旋转动画、缩放动画和路径动画
注意:引入three.js三维引擎的路径需要根据 自己的情况修改相应的路径,本示例采用引用外部模块的方式。
以下为完整代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>路径动画+缩放动画+旋转动画+移动动画</title>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
div {
width: 100%;
height: 100%;
position: absolute;
top: 0;
/* left: 0; */
}
.buttons {
position: absolute;
top: 0;
right: 0;
width: 20%;
height: 10%;
/* background-color: darkgrey; */
z-index: 999;
}
input {
width: 100%;
cursor: pointer;
}
</style>
</head>
<body>
<div class="buttons">
<input id='startBecomeBig' type="button" value="缩放动画-开始变大">
<input id='startBecomeSmall' type="button" value="缩放动画-开始变小">
<input id="stopall" type="button" value="缩放动画-停止">
<input id='startRotate' type="button" value="旋转动画-开始">
<input id="stopRotate" type="button" value="旋转动画-停止">
<input id='startMove' type="button" value="移动动画-开始">
<input id="stopMove" type="button" value="移动动画-停止">
<input id='start' type="button" value="路径动画-开始">
<input id="stop" type="button" value="路径动画-暂停">
<input id='end' type="button" value="移动路径终点">
<input id='toggle' type="button" value="切换路径动画视角">
<!-- <input id='cube' type="button" value="增加立方体"> -->
</div>
<script type="module">
import * as THREE from '../three.js-dev-r140/three.js-dev/build/three.module.js';
import { OrbitControls } from '../jsm/OrbitControls.js';
import { zdyScaleBecomeBig, zdyScaleBecomeSmall } from '../srcmodule/ScaleAnimation.js';
import { zdyRotate } from '../srcmodule/RotateAnimation.js';
import { zdyMove } from '../srcmodule/MoveAnimation.js';
import { onMouseClickToRed } from '../srcmodule/onMouseClickToRed.js';
var x1 = 0.01;
var y1 = 0.01;
var z1 = 0.01;
var power = false; //定义初始状态,动画是停止状态。如果进行了一次点击,将power 改变为true,再进行一次点击, true变为false
var id = null;
var move_x1 = 0.55;
var move_y1 = 0.88;
var move_z1 = 0.10;
let scene = new THREE.Scene();
scene.background = new THREE.Color('gray');
let camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.set(250, 250, 250);
let renderer = new THREE.WebGLRenderer({ alpha: false });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
/*
*下面代码表示增加鼠标控制
*/
let controls = new OrbitControls(camera, renderer.domElement);//鼠标控制
{
let directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
let light = new THREE.AmbientLight(0x404040); // soft white light
scene.add(light);
let axesHelper = new THREE.AxesHelper(500);
scene.add(axesHelper);
}
/************场景布置结束**************/
let material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); //设置材质
let geometry = new THREE.CylinderBufferGeometry(0, 10, 50, 12); //设置物体,本例中为圆柱缓冲几何体
geometry.rotateX(Math.PI / 2);
let cone = new THREE.Mesh(geometry, material);
scene.add(cone); //场景中添加CylinderBufferGeometry 圆柱圆锥缓冲几何体本案例的中的箭头
var mesh = new THREE.Mesh(new THREE.BoxGeometry(20, 15, 10), new THREE.MeshBasicMaterial({
color: 0x0051ba,
wireframe: false
}));
scene.add(mesh); //场景中增加立方体
function render() {
renderer.render(scene, camera); //封装一个渲染函数,调用一次渲染一次
}
function startBecomeBig() {
if (power == true) {
console.log('当前放大动画已开始');
}
else {
drawBecomeBig();
//id = requestAnimationFrame(draw);
power = true;
}
}
function startBecomeSmall() {
if (power == true) {
console.log('当前缩小动画已开始');
}
else {
drawBecomeSmall();
//id = requestAnimationFrame(drawBecomeSmall);
power = true;
}
}
function startRotate() {
if (power == true) {
console.log('当前旋转动画已开始');
}
else {
drawRot();
//id = requestAnimationFrame(drawBecomeSmall);
power = true;
}
}
function startMove() {
if (power == true) {
console.log('当前移动动画已开始');
}
else {
drawMov();
power = true;
}
}
function stop() {
if (power == true) {
cancelAnimationFrame(id);
id = null;
power = false;
}
else {
console.log('当前动画已经停止了')
// power = false;
}
}
function drawBecomeBig() {
zdyScaleBecomeBig(renderer, mesh, scene, camera, x1, y1, z1);// 调用外部的缩放变大函数
renderer.render(scene, camera);
id = requestAnimationFrame(drawBecomeBig);
}
function drawBecomeSmall() {
zdyScaleBecomeSmall(renderer, mesh, scene, camera, x1, y1, z1);// 调用外部的缩放变小函数
renderer.render(scene, camera);
id = requestAnimationFrame(drawBecomeSmall);
}
function drawRot() {
zdyRotate(renderer, mesh, scene, camera, x1, y1, z1);// 调用外部的旋转函数
renderer.render(scene, camera);
id = requestAnimationFrame(drawRot);
}
function drawMov() {
zdyMove(renderer, mesh, scene, camera, move_x1, move_y1, move_z1);// 调用外部的移动函数
renderer.render(scene, camera);
id = requestAnimationFrame(drawMov);
}
document.getElementById('startBecomeBig').onclick = function () {
// stop();
console.log("你点击了开始变大按钮");
// draw();
startBecomeBig();
};
document.getElementById('startBecomeSmall').onclick = function () {
id = null;
// stop();
console.log("你点击了开始变小按钮");
// drawBecomeSmall();
startBecomeSmall();
};
document.getElementById('stopall').onclick = function () {
console.log('您点击了停止动画按钮');
// cancelAnimationFrame(id);
// id = null;
// power = false;
stop();
// console.log(power);
};
document.getElementById('startRotate').onclick = function () {
id = null;
console.log("你点击了开始旋转按钮");
startRotate();
};
document.getElementById('stopRotate').onclick = function () {
console.log('您点击了停止旋转按钮');
// cancelAnimationFrame(id);
// id = null;
// power = false;
stop();
// console.log(power);
};
document.getElementById('startMove').onclick = function () {
id = null;
console.log("你点击了开始移动按钮");
startMove();
};
document.getElementById('stopMove').onclick = function () {
console.log('您点击了停止移动按钮');
// cancelAnimationFrame(id);
// id = null;
// power = false;
stop();
// console.log(power);
};
//自定义路径类
class myPath {
constructor(array) {
//将传进来的数组转换为Vec3集合
let pointsArr = [];
if (array.length % 3 !== 0) {
console.error('错误,数据的个数非3的整数倍!', array);
return null;
}
for (let index = 0; index < array.length; index += 3) {
pointsArr.push(new THREE.Vector3(array[index], array[index + 1], array[index + 2]));
}
//顶点位置三维向量数组
this.pointsArr = pointsArr;
//设置折线几何体
this.line = null;
{
let lineMaterial = new THREE.LineBasicMaterial({
color: 0xff00ff
});
let lineGeometry = new THREE.BufferGeometry().setFromPoints(pointsArr);
this.line = new THREE.Line(lineGeometry, lineMaterial);
}
//设置锚点几何体
this.points = null;
{
let pointsBufferGeometry = new THREE.BufferGeometry();
pointsBufferGeometry.setAttribute('position', new THREE.Float32BufferAttribute(array, 3));
let pointsMaterial = new THREE.PointsMaterial({ color: 0xffff00, size: 10 });
this.points = new THREE.Points(pointsBufferGeometry, pointsMaterial);
}
//计算每个锚点在整条折线上所占的百分比
this.pointPercentArr = [];
{
let distanceArr = []; //每段距离
let sumDistance = 0; //总距离
for (let index = 0; index < pointsArr.length - 1; index++) {
distanceArr.push(pointsArr[index].distanceTo(pointsArr[index + 1]));
}
sumDistance = distanceArr.reduce(function (tmp, item) {
return tmp + item;
})
let disPerSumArr = [0];
disPerSumArr.push(distanceArr[0]);
distanceArr.reduce(function (tmp, item) {
disPerSumArr.push(tmp + item);
return tmp + item;
})
disPerSumArr.forEach((value, index) => {
disPerSumArr[index] = value / sumDistance;
})
this.pointPercentArr = disPerSumArr;
}
// console.log(this.pointPercentArr);
//上一次的朝向
this.preUp = new THREE.Vector3(0, 0, 0);
//run函数需要的数据
this.perce = 0; //控制当前位置占整条线百分比
this.speed = 0.0005; //控制是否运动
this.turnFactor = 0; //暂停时间因子
this.turnSpeedFactor = 0.001; //转向速度因子
this.obj = null;
this.preTime = new Date().getTime(); // 获取时间
this.firstTurn = false;
}
//获取点,是否转弯,朝向等
getPoint(percent) {
let indexP = 0;
let indexN = 0;
let turn = false;
for (let i = 0; i < this.pointPercentArr.length; i++) {
if (percent >= this.pointPercentArr[i] && percent < this.pointPercentArr[i + 1]) {
indexN = i + 1;
indexP = i;
if (percent === this.pointPercentArr[i]) {
turn = true;
}
}
}
let factor = (percent - this.pointPercentArr[indexP]) / (this.pointPercentArr[indexN] - this.pointPercentArr[indexP]);
let position = new THREE.Vector3();
position.lerpVectors(this.pointsArr[indexP], this.pointsArr[indexN], factor); //position的计算完全正确
//计算朝向
let up = new THREE.Vector3().subVectors(this.pointsArr[indexN], this.pointsArr[indexP]);
let preUp = this.preUp;
if (this.preUp.x != up.x || this.preUp.y != up.y || this.preUp.z != up.z) {
// console.info('当前朝向与上次朝向不等,将turn置为true!');
turn = true;
}
this.preUp = up;
return {
position,
direction: up,
turn, //是否需要转向
preUp, //当需要转向时的上次的方向
};
}
//定义一个函数run.输入参数包括:是否运动,运动的对象,是否运动到结尾
run(animata, camera, end) {
if (end) {
this.perce = 0.99999;
this.obj = this.getPoint(this.perce);
//修改位置
let posi = this.obj.position;
// cone.position.set(posi.x, posi.y, posi.z);
camera.position.set(posi.x, posi.y, posi.z); //相机漫游2
}
else if (animata) {
//转弯时
if (this.obj && this.obj.turn) {
if (this.turnFactor == 0) {
this.preTime = new Date().getTime();
this.turnFactor += 0.000000001;
}
else {
let nowTime = new Date().getTime();
let timePass = nowTime - this.preTime;
this.preTime = nowTime;
this.turnFactor += this.turnSpeedFactor * timePass;
}
// console.log('--->>> 当前需要turn , turnFactor值为 :', this.turnFactor);
if (this.turnFactor > 1) {
this.turnFactor = 0;
this.perce += this.speed;
this.obj = this.getPoint(this.perce);
}
else {
//修改朝向 (向量线性插值方式)
let interDirec = new THREE.Vector3();//实例化向量
interDirec.lerpVectors(this.obj.preUp, this.obj.direction, this.turnFactor);
let look = new THREE.Vector3();
look = look.add(this.obj.position);
look = look.add(interDirec);
// cone.lookAt(look);
camera.lookAt(look); //相机漫游1
}
}
//非转弯时
else {
this.obj = this.getPoint(this.perce);
//修改位置
let posi = this.obj.position;
// cone.position.set(posi.x, posi.y, posi.z);
camera.position.set(posi.x, posi.y, posi.z); //相机漫游2
//当不需要转向时进行
if (!this.obj.turn) {
let look = posi.add(this.obj.direction);
// cone.lookAt(look);
camera.lookAt(look); //相机漫游3
}
this.perce += this.speed;
}
}
}
}
/*
定义物体移动的路径
*/
let a = new myPath([
0, 0, 0,
200, 200, 0,
400, 0, 0,
0, -300, 0,
-300, -100, 0,
100, 500, 0,
500, 350, 0,
// 700, 100, 500,
// 300, 100, 800,
]);
scene.add(a.points);
scene.add(a.line);
render(); //执行初始的渲染动画
let startFlag = true;
let endFlag = false;
let toggleFlag = true;
let runMesh = cone; //定义圆锥体为移动对象
document.getElementById('start').onclick = function timeStart() {
console.log('点击了路径动画开始');
startFlag = true; //点击开始的时候 将startFlag改为true
endFlag = false; //点击开始的时候 将endFlag改为false
power = true;
animateLL();//执行路径渲染动画
};
document.getElementById('stop').onclick = function timeStart() {
console.log('点击了路径动画暂停');
startFlag = false; //点击暂停的时候 将startFlag改为false
};
document.getElementById('end').onclick = function timeStart() {
console.log('点击了路径动画 物体移动到终点');
endFlag = true; //点击end的时候 将endFlag改为true
};
/*
以下代码表示相机视角和 物体视角的互相切换功能
*/
document.getElementById('toggle').onclick = function timeStart() {
console.log('点击了视角切换');
toggleFlag = !toggleFlag; //点击toggle的时候 将toggleFlag由真变为假,或者由假变为真;
if (toggleFlag) { //如果toggleFlag 是真的,把cone赋值给runMesh,并设置相机的位置;
runMesh = cone;
camera.position.set(500, 500, 500);
}
else {
runMesh = camera; //如果toggleFlag 是假,把相机赋值给runMesh,并设置相机的位置;
}
};
onMouseClickToRed(camera, scene, renderer); //调用外部的选中变红色函数,选中物体之后 选中的物体会变红色
/*
*以下定义一个动画渲染函数
*/
function animateLL() {
if (power == false) {
console.log("设置初始状态,路径动画未开始,请点击开始路径动画按钮开始路径动画");
}
else {
animate();
};
}
// animateLL();//执行路径渲染动画
function animate() {
let animation = function () {
requestAnimationFrame(animation); //调用自身 重复渲染
controls.update();//更新控制
a.run(startFlag, runMesh, endFlag);
//路程循环
if (a.perce >= 1) {
a.perce = 0;
}
renderer.render(scene, camera);
}
animation(); //不能缺这个调用函数的的语句,否则 只是定义了animation 函数里面并没有执行
}
animateLL();//执行路径渲染动画
</script>
</body>
</html>
外部模块 之 MoveAnimation.js 的代码如下:
{/* <script type="module"> */}
import * as THREE from '../three.js-dev-r140/three.js-dev/build/three.module.js';
// import { OrbitControls } from '../jsm/OrbitControls.js';
{/* <script> */}
function zdyMove(_renderer,_mesh,_scene,_camera,_x1,_y1,_z1) {
_mesh.position.x += _x1; //利用mesh的.position属性
_mesh.position.y += _y1; //利用mesh的.position属性
_mesh.position.z += _z1; //利用mesh的.position属性
_renderer.render(_scene, _camera);
}
export {zdyMove};
外部模块 之 RotateAnimation.js 的代码如下:
{/* <script type="module"> */}
import * as THREE from '../three.js-dev-r140/three.js-dev/build/three.module.js';
// import { OrbitControls } from '../jsm/OrbitControls.js';
{/* <script> */}
function zdyRotate(_renderer,_mesh,_scene,_camera,_x1,_y1,_z1) {
_mesh.rotation.x += _x1; //利用mesh的.scale属性
_mesh.rotation.y += _y1; //利用mesh的.scale属性
_mesh.rotation.z += _z1; //利用mesh的.scale属性
_renderer.render(_scene, _camera);
}
export {zdyRotate};
外部模块 之ScaleAnimation.js 的代码如下:
{/* <script type="module"> */}
import * as THREE from '../three.js-dev-r140/three.js-dev/build/three.module.js';
// import { OrbitControls } from '../jsm/OrbitControls.js';
{/* <script> */}
function zdyScaleBecomeBig(_renderer,_mesh,_scene,_camera,_x1,_y1,_z1) {
_mesh.scale.x += _x1; //利用mesh的.scale属性
_mesh.scale.y += _y1; //利用mesh的.scale属性
_mesh.scale.z += _z1; //利用mesh的.scale属性
_renderer.render(_scene, _camera);
}
function zdyScaleBecomeSmall(renderer,mesh,scene,camera,x1,y1,z1) {
mesh.scale.x -= x1; //利用mesh的.scale属性
mesh.scale.y -= y1; //利用mesh的.scale属性
mesh.scale.z -= z1; //利用mesh的.scale属性
renderer.render(scene, camera);
}
export {zdyScaleBecomeBig, zdyScaleBecomeSmall};
外部模块 之 onMouseClickToRed.js (作用是 点击物体后该物体自动变红色)的代码如下:
import * as THREE from '../three.js-dev-r140/three.js-dev/build/three.module.js';
// import {
// EventDispatcher,
// MOUSE,
// Quaternion,
// Spherical,
// TOUCH,
// Vector2,
// Vector3
// } from '../three.js-dev-r140/three.js-dev/build/three.module.js';
function onMouseClickToRed(camera,scene,renderer){
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
document.addEventListener('click', onMouseClick);
function onMouseClick(event) {
//将鼠标点击位置的屏幕坐标转换成threejs中的标准坐标
mouse.x = (event.clientX / window.innerWidth) * 2 - 1
mouse.y = -((event.clientY / window.innerHeight) * 2 - 1)
// console.log("mouse:"+mouse.x+","+mouse.y)
// 通过鼠标点的位置和当前相机的矩阵计算出raycaster
raycaster.setFromCamera(mouse, camera);
// 获取raycaster直线和所有模型相交的数组集合
var intersects = raycaster.intersectObjects(scene.children);
console.log(intersects);
//将所有的相交的模型的颜色设置为红色
for (var i = 0; i < intersects.length; i++) {
intersects[i].object.material.color.set(0xff0000);
}
renderer.render(scene,camera); //修改之后要重新渲染一下才能显示出来,否则虽然修改了属性但是没渲染就不会变颜色
}
}
export {onMouseClickToRed};