以下代码 示例了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变为falsevar 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 lightscene.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改为trueendFlag = false;   //点击开始的时候 将endFlag改为falsepower = 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 - 1mouse.y = -((event.clientY / window.innerHeight) * 2 - 1)// console.log("mouse:"+mouse.x+","+mouse.y)// 通过鼠标点的位置和当前相机的矩阵计算出raycasterraycaster.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};

Threejs开发之移动动画、旋转动画、缩放动画和路径动画相关推荐

  1. 【SwiftUI模块】0008、SwiftUI-自定义启动闪屏动画-App启动闪屏曲线路径动画

    SwiftUI小功能模块系列 0001.SwiftUI自定义Tabbar动画效果 0002.SwiftUI自定义3D动画导航抽屉效果 0003.SwiftUI搭建瀑布流-交错网格-效果 0004.Sw ...

  2. android过渡动画旋转,炫酷的Android过渡动画

    [桃花潭水深千尺,不及汪伦送我情] 不知道大家有没有发现,Android版的掘金有下面这个小小动画:点击作者头像跳转到作者的详情页,而作者头像会从当前界面通过动画过渡详情页界面. image 知识贫乏 ...

  3. 官方新动作!老子云3D开发SDK又更新:新增3D测量,路径动画

    近期老子云SDK新增了3D测量.路径动画(新版)两大开发功能,这也是首次在SDK中开放3D测量功能,开发者用户反响十分热烈! 我们进入开发者示例代码页面,就可以看到左侧栏多了"动画路径.3D ...

  4. ios开发 方形到圆的动画_iOS利用UIBezierPath + CAAnimation实现路径动画效果

    前言 上次给大家介绍了iOS利用UIBezierPath + CAAnimation实现路径动画效果的相关内容,今天实现一个根据心跳路径实现一个路径动画,让某一视图沿着路径进行运动.. 效果图如下: ...

  5. HTML CSS3变形移动、旋转、缩放、3d 、动画 拉伸布局等笔记

    变形移动 <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8&q ...

  6. Silverlight Blend动画设计系列十一:沿路径动画(Animation Along a Path)

    Silverlight 提供一个好的动画基础,但缺少一种方便的方法沿任意几何路径对象进行动画处理.在Windows Presentation Foundation中提供了动画处理类DoubleAnim ...

  7. android+动画+锯齿,Android_rotate--animation 动画旋转两图片,消除动画锯齿现象 android 开发:动画旋转两图片 - 下载 - 搜珍网...

    Android+动画旋转两图/ Android+动画旋转两图/.classpath Android+动画旋转两图/.project Android+动画旋转两图/.settings/ Android+ ...

  8. Unity 编辑器开发实战【Custom Editor】- 为UI视图制作动画编辑器

    为了更方便地为UI视图添加动画,将动画的编辑功能封装在了UI View类中,可以通过编辑器快速的为视图编辑动画.动画分为两种类型,一种是Unity中的Animator动画,该类型直接通过一个字符串类型 ...

  9. Android自定义控件开发入门与实战(6)路径动画,android脚本开发工具

    前面几章所讲的内容其实都只是比较普通.简单的动画,这章开始学习较难.较为有深度.也比较可以实现更加炫酷效果的动画,通过PathMeasure和SVG动画来实现. PathMeasure实现路径动画 P ...

最新文章

  1. Spark入门教程(二)Spark2.2源码编译及安装配置
  2. 智能车竞赛车模轮子与电机齿轮的参数
  3. 利用JSP编写程序初步
  4. 工作经常使用的SQL整理,实战篇(一)
  5. 【Android开发】NDK开发(1)-Hello World!
  6. MySQL删除数据库
  7. 视力差,不要怕!PNAS:服用超长链多不饱和脂肪酸可显著改善视觉和视网膜功能!...
  8. .net无刷新验证码
  9. 深度学习笔记——循环神经网络RNN/LSTM
  10. 升级总代分享思路_旧笔记本光驱换SSD,升级内存,改造散热还能再战5年
  11. (BFS) bzoj 1102
  12. matlab%低通滤波器设计,matlab 低通滤波器设计及实现
  13. 同时使用动态库和静态库时怎么写makefile
  14. 项目部署到服务器显示 网页无法访问500 错误的解决办法
  15. Qt自定义标题栏可拖动修改窗口大小
  16. C#设计模式——访问者模式(Vistor Pattern)
  17. 【云和恩墨业务介绍】之 SQL 审核服务
  18. “%,/,//”的用法
  19. 马氏链,Metropolis-Hastings采样与Gibbs采样的理解(附有python仿真)
  20. 期货法律法规重点笔记1

热门文章

  1. 智能电器控制板EMC仿真与优化
  2. 作文以记之 ~ 克隆图
  3. 回顾2011年所经历的事,那些难忘的事
  4. 【DDR3 控制器设计】(4)DDR3 的读操作设计
  5. spark dataframe 数据类型转换
  6. 手持终端在仓库盘点中的优势
  7. 如何让6自由度双足机器人实现翻跟头的动作?
  8. ::细细品味ASP.NET (二):: 1
  9. R语言绘制IPCC风格箱线抖动点图
  10. 公摊面积用计算机怎么计算,公摊面积如何计算?