书籍名称:HTML5-Animation-with-JavaScript

书籍源码:https://github.com/lamberta/html5-animation


1.在正选函数中,随角度的增大,sin的值徘徊在正一和负一之间。如下图。这可以用做物体的来回运动。

2.动画源码

index.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Bobbing 2</title>
  6. <link rel="stylesheet" href="../include/style.css">
  7. </head>
  8. <body>
  9. <header>
  10. Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
  11. </header>
  12. <canvas id="canvas" width="400" height="400"></canvas>
  13.  
  14. <script src="../include/utils.js"></script>
  15. <script src="./classes/ball.js"></script>
  16. <script>
  17. window.onload = function () {
  18. var canvas = document.getElementById('canvas'),
  19. context = canvas.getContext('2d'),
  20. ball = new Ball(),
  21. angle = 0,
  22. centerY = 200,
  23. range = 50,
  24. speed = 0.05;
  25.  
  26. ball.x = canvas.width / 2;
  27.  
  28. (function drawFrame () {
  29. window.requestAnimationFrame(drawFrame, canvas);
  30. context.clearRect(0, 0, canvas.width, canvas.height);
  31.  
  32. ball.y = centerY + Math.sin(angle) * range;
  33. angle += speed;
  34. ball.draw(context);
  35. }());
  36. };
  37. </script>
  38. </body>
  39. </html>

style.css

  1. /* Some HTML5 Tags
  2. */
  3.  
  4. aside, footer, header, nav, section {
  5. display: block;
  6. }
  7.  
  8. /* Examples
  9. */
  10.  
  11. body {
  12. background-color: #bbb;
  13. color: #383838;
  14. }
  15.  
  16. #canvas {
  17. background-color: #fff;
  18. }
  19.  
  20. header {
  21. padding-bottom: 10px;
  22. }
  23.  
  24. header a {
  25. color: #30f;
  26. text-decoration: none;
  27. }
  28.  
  29. aside {
  30. padding-top: 6px;
  31. }
  32.  
  33. /* Index page
  34. */
  35.  
  36. #index-body {
  37. background-color: #fdeba1;
  38. font-family: "Vollkorn", serif;
  39. color: #000;
  40. }
  41.  
  42. #index-body a {
  43. text-decoration: none;
  44. color: #b30300;
  45. }
  46.  
  47. #index-body #description, #index-body #exercises {
  48. overflow: auto;
  49. max-width: 900px;
  50. margin: 0px auto 20px auto;
  51. padding-left: 15px;
  52. padding-bottom: 15px;
  53. background-color: #fff;
  54. border-radius: 15px;
  55. }
  56.  
  57. #index-body #description {
  58. margin-top: 40px;
  59. }
  60.  
  61. #index-body h1 {
  62. color: #b30300;
  63. }
  64.  
  65. #index-body #description h2 {
  66. margin-bottom:;
  67. }
  68.  
  69. #index-body h1 a {
  70. text-decoration: underline;
  71. color: #b30300;
  72. }
  73.  
  74. #index-body li h2, #index-body li h3, #index-body li h4 {
  75. color: #000;
  76. }
  77.  
  78. #index-body li h3 {
  79. margin-bottom: 0px;
  80. }
  81.  
  82. #index-body #description ul {
  83. margin:;
  84. padding:;
  85. list-style-type: none;
  86. }
  87.  
  88. #index-body #description ul li {
  89. padding-bottom: 0.6em;
  90. }
  91. .container {
  92. display: table;
  93. width: 100%;
  94. height: auto;
  95. }
  96. .container .text {
  97. display:table-cell;
  98. height:100%;
  99. vertical-align:middle;
  100. }
  101. .container img {
  102. padding: 0 20px;
  103. display: block;
  104. float: right;
  105. }
  106. .container .clear {
  107. clear: both;
  108. }
  109.  
  110. #exercises ul {
  111. margin:;
  112. padding: 4px 20px 10px 20px;
  113. }
  114.  
  115. #exercises ol {
  116. margin: 0 20px 10px 0;
  117. padding:;
  118. list-style-type: none;
  119. }
  120.  
  121. #exercises ol li {
  122. padding-top: 5px;
  123. }
  124.  
  125. #exercises ol ol ol {
  126. padding-left: 60px;
  127. list-style-type: decimal-leading-zero;
  128. }
  129.  
  130. #exercises ol ol ol li img, #exercises ol ol li img {
  131. margin-left: 4px;
  132. margin-bottom: -10;
  133. }
  134.  
  135. #exercises h2 {
  136. margin: 10px 0 0 0;
  137. }

utils.js

  1. /**
  2. * Normalize the browser animation API across implementations. This requests
  3. * the browser to schedule a repaint of the window for the next animation frame.
  4. * Checks for cross-browser support, and, failing to find it, falls back to setTimeout.
  5. * @param {function} callback Function to call when it's time to update your animation for the next repaint.
  6. * @param {HTMLElement} element Optional parameter specifying the element that visually bounds the entire animation.
  7. * @return {number} Animation frame request.
  8. */
  9. if (!window.requestAnimationFrame) {
  10. window.requestAnimationFrame = (window.webkitRequestAnimationFrame ||
  11. window.mozRequestAnimationFrame ||
  12. window.msRequestAnimationFrame ||
  13. window.oRequestAnimationFrame ||
  14. function (callback) {
  15. return window.setTimeout(callback, 17 /*~ 1000/60*/);
  16. });
  17. }
  18.  
  19. /**
  20. * ERRATA: 'cancelRequestAnimationFrame' renamed to 'cancelAnimationFrame' to reflect an update to the W3C Animation-Timing Spec.
  21. *
  22. * Cancels an animation frame request.
  23. * Checks for cross-browser support, falls back to clearTimeout.
  24. * @param {number} Animation frame request.
  25. */
  26. if (!window.cancelAnimationFrame) {
  27. window.cancelAnimationFrame = (window.cancelRequestAnimationFrame ||
  28. window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
  29. window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame ||
  30. window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame ||
  31. window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame ||
  32. window.clearTimeout);
  33. }
  34.  
  35. /* Object that contains our utility functions.
  36. * Attached to the window object which acts as the global namespace.
  37. */
  38. window.utils = {};
  39.  
  40. /**
  41. * Keeps track of the current mouse position, relative to an element.
  42. * @param {HTMLElement} element
  43. * @return {object} Contains properties: x, y, event
  44. */
  45. window.utils.captureMouse = function (element) {
  46. var mouse = {x: 0, y: 0, event: null},
  47. body_scrollLeft = document.body.scrollLeft,
  48. element_scrollLeft = document.documentElement.scrollLeft,
  49. body_scrollTop = document.body.scrollTop,
  50. element_scrollTop = document.documentElement.scrollTop,
  51. offsetLeft = element.offsetLeft,
  52. offsetTop = element.offsetTop;
  53.  
  54. element.addEventListener('mousemove', function (event) {
  55. var x, y;
  56.  
  57. if (event.pageX || event.pageY) {
  58.  
  59. x = event.pageX;
  60. y = event.pageY;
  61. } else {
  62. x = event.clientX + body_scrollLeft + element_scrollLeft;
  63. y = event.clientY + body_scrollTop + element_scrollTop;
  64. }
  65. x -= offsetLeft;
  66. y -= offsetTop;
  67.  
  68. mouse.x = x;
  69. mouse.y = y;
  70. mouse.event = event;
  71. }, false);
  72.  
  73. return mouse;
  74. };
  75.  
  76. /**
  77. * Keeps track of the current (first) touch position, relative to an element.
  78. * @param {HTMLElement} element
  79. * @return {object} Contains properties: x, y, isPressed, event
  80. */
  81. window.utils.captureTouch = function (element) {
  82. var touch = {x: null, y: null, isPressed: false, event: null},
  83. body_scrollLeft = document.body.scrollLeft,
  84. element_scrollLeft = document.documentElement.scrollLeft,
  85. body_scrollTop = document.body.scrollTop,
  86. element_scrollTop = document.documentElement.scrollTop,
  87. offsetLeft = element.offsetLeft,
  88. offsetTop = element.offsetTop;
  89.  
  90. element.addEventListener('touchstart', function (event) {
  91. touch.isPressed = true;
  92. touch.event = event;
  93. }, false);
  94.  
  95. element.addEventListener('touchend', function (event) {
  96. touch.isPressed = false;
  97. touch.x = null;
  98. touch.y = null;
  99. touch.event = event;
  100. }, false);
  101.  
  102. element.addEventListener('touchmove', function (event) {
  103. var x, y,
  104. touch_event = event.touches[0]; //first touch
  105.  
  106. if (touch_event.pageX || touch_event.pageY) {
  107. x = touch_event.pageX;
  108. y = touch_event.pageY;
  109. } else {
  110. x = touch_event.clientX + body_scrollLeft + element_scrollLeft;
  111. y = touch_event.clientY + body_scrollTop + element_scrollTop;
  112. }
  113. x -= offsetLeft;
  114. y -= offsetTop;
  115.  
  116. touch.x = x;
  117. touch.y = y;
  118. touch.event = event;
  119. }, false);
  120.  
  121. return touch;
  122. };
  123.  
  124. /**
  125. * Returns a color in the format: '#RRGGBB', or as a hex number if specified.
  126. * @param {number|string} color
  127. * @param {boolean=} toNumber=false Return color as a hex number.
  128. * @return {string|number}
  129. */
  130. window.utils.parseColor = function (color, toNumber) {
  131. if (toNumber === true) {
  132. if (typeof color === 'number') {
  133. return (color | 0); //chop off decimal
  134. }
  135. if (typeof color === 'string' && color[0] === '#') {
  136. color = color.slice(1);
  137. }
  138. return window.parseInt(color, 16);
  139. } else {
  140. if (typeof color === 'number') {
  141. color = '#' + ('00000' + (color | 0).toString(16)).substr(-6); //pad
  142. }
  143. return color;
  144. }
  145. };
  146.  
  147. /**
  148. * Converts a color to the RGB string format: 'rgb(r,g,b)' or 'rgba(r,g,b,a)'
  149. * @param {number|string} color
  150. * @param {number} alpha
  151. * @return {string}
  152. */
  153. window.utils.colorToRGB = function (color, alpha) {
  154. //number in octal format or string prefixed with #
  155. if (typeof color === 'string' && color[0] === '#') {
  156. color = window.parseInt(color.slice(1), 16);
  157. }
  158. alpha = (alpha === undefined) ? 1 : alpha;
  159. //parse hex values
  160. var r = color >> 16 & 0xff,
  161. g = color >> 8 & 0xff,
  162. b = color & 0xff,
  163. a = (alpha < 0) ? 0 : ((alpha > 1) ? 1 : alpha);
  164. //only use 'rgba' if needed
  165. if (a === 1) {
  166. return "rgb("+ r +","+ g +","+ b +")";
  167. } else {
  168. return "rgba("+ r +","+ g +","+ b +","+ a +")";
  169. }
  170. };
  171.  
  172. /**
  173. * Determine if a rectangle contains the coordinates (x,y) within it's boundaries.
  174. * @param {object} rect Object with properties: x, y, width, height.
  175. * @param {number} x Coordinate position x.
  176. * @param {number} y Coordinate position y.
  177. * @return {boolean}
  178. */
  179. window.utils.containsPoint = function (rect, x, y) {
  180. return !(x < rect.x ||
  181. x > rect.x + rect.width ||
  182. y < rect.y ||
  183. y > rect.y + rect.height);
  184. };
  185.  
  186. /**
  187. * Determine if two rectangles overlap.
  188. * @param {object} rectA Object with properties: x, y, width, height.
  189. * @param {object} rectB Object with properties: x, y, width, height.
  190. * @return {boolean}
  191. */
  192. window.utils.intersects = function (rectA, rectB) {
  193. return !(rectA.x + rectA.width < rectB.x ||
  194. rectB.x + rectB.width < rectA.x ||
  195. rectA.y + rectA.height < rectB.y ||
  196. rectB.y + rectB.height < rectA.y);
  197. };

ball.js

  1. function Ball (radius, color) {
  2. if (radius === undefined) { radius = 40; }
  3. if (color === undefined) { color = "#ff0000"; }
  4. this.x = 0;
  5. this.y = 0;
  6. this.radius = radius;
  7. this.rotation = 0;
  8. this.scaleX = 1;
  9. this.scaleY = 1;
  10. this.color = utils.parseColor(color);
  11. this.lineWidth = 1;
  12. }
  13.  
  14. Ball.prototype.draw = function (context) {
  15. context.save();
  16. context.translate(this.x, this.y);
  17. context.rotate(this.rotation);
  18. context.scale(this.scaleX, this.scaleY);
  19.  
  20. context.lineWidth = this.lineWidth;
  21. context.fillStyle = this.color;
  22. context.beginPath();
  23. //x, y, radius, start_angle, end_angle, anti-clockwise
  24. context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
  25. context.closePath();
  26. context.fill();
  27. if (this.lineWidth > 0) {
  28. context.stroke();
  29. }
  30. context.restore();
  31. };

3.波动实际是在上下移动的基础上x一直递增。

在原页面index.html的基础上简单修改一下就可以

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Bobbing 2</title>
  6. <link rel="stylesheet" href="../include/style.css">
  7. </head>
  8. <body>
  9. <header>
  10. Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
  11. </header>
  12. <canvas id="canvas" width="400" height="400"></canvas>
  13.  
  14. <script src="../include/utils.js"></script>
  15. <script src="./classes/ball.js"></script>
  16. <script>
  17. window.onload = function () {
  18. var canvas = document.getElementById('canvas'),
  19. context = canvas.getContext('2d'),
  20. ball = new Ball(),
  21. angle = 0,
  22. centerY = 200,
  23. range = 50,
  24. xspeed = 1,
  25. speed = 0.05;
  26.  
  27. ball.x = canvas.width / 2;
  28.  
  29. (function drawFrame () {
  30. window.requestAnimationFrame(drawFrame, canvas);
  31. context.clearRect(0, 0, canvas.width, canvas.height);
  32. ball.x += xspeed;
  33. ball.y = centerY + Math.sin(angle) * range;
  34. angle += speed;
  35. ball.draw(context);
  36. }());
  37. };
  38. </script>
  39. </body>
  40. </html>

动画原理——线性来回运动&&波动的更多相关文章

  1. Atitit 视频编码与动画原理attilax总结

    Atitit 视频编码与动画原理attilax总结 1.1. 第一步:实现有损图像压缩和解压1 1.2. 接着将其量化,所谓量化,就是信号采样的步长,1 1.3. 第二步:实现宏块误差计算2 1.4. ...

  2. iOS动画原理

    1. iOS动画原理 本质:动画对象(这里是UIView)的状态,基于时间变化的反应 分类:可以分为显式动画(关键帧动画和逐帧动画)和隐式动画 关键帧和逐帧总结:关键帧动画的实现方式,只需要修改某个属 ...

  3. Unity3D 骨骼动画原理学习笔记

    最近研究了一下游戏中模型的骨骼动画的原理,做一个学习笔记,便于大家共同学习探讨. ps:最近改bug改的要死要活,博客写的吭哧吭哧的~ 首先列出学习参考的前人的文章,本文较多的参考了其中的表述: 1. ...

  4. OpenGL10-骨骼动画原理篇(2)

    接上一篇的内容,上一篇,简单的介绍了,骨骼动画的原理,给出来一个 简单的例程,这一例程将给展示一个最初级的人物动画,具备多细节内容 以人走路为例子,当人走路的从一个站立开始,到迈出一步,这个过程是 一 ...

  5. js中动画原理

    现如今,许多页面上均有一些动画效果.适当的动画效果可以在一定程度上提高页面的美观度,具有提示效果的动画可以增强页面的易用性. 实现页面动画的途径一般有两种. 一种是通过操作JavaScript间接操作 ...

  6. SVG描边动画原理

    SVG描边动画原理其实很简单,主要利用以下两个属性 stroke-dasharray 制作虚线,使得黑白相间, stroke-dashoffset 使得虚线向开头偏移,这里的1500不精确,是我随便取 ...

  7. JS实现动画原理一(闭包方式)

    前提:      你必须了解js的闭包(否则你看不懂滴)     我们就来做一个js实现jq animate的动画效果来简单探索一下,js动画实现的简单原理: html代码 <div id=&q ...

  8. JS 实现无缝滚动动画原理(初学者入)

    这段时间在教培训班的学生使用原生javascript实现无缝滚动的动画案例,做了这个原理演示的动画,分享给自学JS的朋友!博主希望对你们有帮助! 在讲解之前先看一下demo: demo:https:/ ...

  9. OpenGL10-骨骼动画原理篇(3)-Shader版本代码已经上传

    视频教程请关注 http://edu.csdn.net/lecturer/lecturer_detail?lecturer_id=440 接上一个例程OpenGL10-骨骼动画原理篇(2),对骨骼动画 ...

随机推荐

  1. SQL Server 2008数据库的一些基本概念 区、页、行

    原文地址:http://www.cnblogs.com/liuzhendong/archive/2011/10/11/2207361.html 以前总是没弄明白这些基本概念,现在整理如下: 1.区: ...

  2. Java报表开发组件DynamicReports

    DynamicReports 是一个基于 JasperReports 进行扩展的 Java 报表库,可用它来快速创建报表而无需可视化报表设计工具. From :  http://www.oschina ...

  3. Unable to resolve target 'android-XX'的问题解决

    1.问题现象(Unable to resolve target 'android-XX') 将低版本的代码导入eclipse时,常遇到这样的问题:Unable to resolve target 'a ...

  4. hdu 4686 Arc of Dream(矩阵快速幂乘法)

    Problem Description An Arc of Dream is a curve defined by following function: where a0 = A0 ai = ai- ...

  5. Spring Http Invoker

    配置例如以下: ①web.xml配置 <servlet> <servlet-name>remote</servlet-name> <servlet-class ...

  6. Bctf-pwn_ruin-re_lastflower

    Pwn-ruin 用几个词来概括下漏洞原理:Arm+heap overflow(house of force)+dl-resolve Info leak: 在printf key8时,泄漏堆上地址(s ...

  7. git clone 命令报错 +diffie-hellman-group1-sha1

    解决方法: 在.ssh目录下新建文件config , 添加 Host * KexAlgorithms +diffie-hellman-group1-sha1 到文件config,即可.

  8. mysql 查询表的行数和空间使用及其它信息

    use information_schema; select concat(round(sum(DATA_LENGTH/1024/1024), 2), 'MB') as data from TABLE ...

  9. 用apiCloud开发应用

    使用apiCloud开发应用就是用html5写页面,css实现样式,js写功能.一套代码在android和ios上都能运行.节省开发周期和人员开销. 代码可以放到云服务器,可以云端打包,云端更新. a ...

  10. 下载PHPDroid: 基于WebView和PHP内置HTTP服务器开发Android应用

    基于Android上的PHP(比如我打包的PHPDroid),寥寥几行PHP代码,就能实现一个支持无线局域网用浏览器访问的Android手机的Shell,用于执行命令和PHP代码.       个人在 ...