动画原理——加速度

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

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

这一章节没有仔细讲一是因为和上一章节很相似,只是速率换成加速度。

二是因为初中学的加速度大家都懂得。

1.在某一方向的方向的加速度

06-acceleration-1.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Acceleration 1</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          ball = new Ball(),
          vx = 0,
          ax = 0.1;

      ball.x = 50;
      ball.y = 100;

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        vx += ax;
        ball.x += vx;
        ball.draw(context);
      }());
    };
    </script>
  </body>
</html>
View Code

2.在两个方向的加速度

08-acceleration-3.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Acceleration 3</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Press arrow keys.</aside>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          ball = new Ball(),
          vx = 0,
          vy = 0,
          ax = 0,
          ay = 0;

      ball.x = canvas.width / 2;
      ball.y = canvas.height / 2;

      window.addEventListener('keydown', function (event) {
        switch (event.keyCode) {
        case 37:      //left
          ax = -0.1;
          break;
        case 39:      //right
          ax = 0.1;
          break;
        case 38:      //up
          ay = -0.1;
          break;
        case 40:      //down
          ay = 0.1;
          break;
        }
      }, false);

      window.addEventListener('keyup', function () {
        ax = 0;
        ay = 0;
      }, false);

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        vx += ax;
        vy += ay;
        ball.x += vx;
        ball.y += vy;
        ball.draw(context);
      }());
    };
    </script>
  </body>
</html>
View Code

3.用三角函数分解的加速度到x,y方向。

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Follow Mouse 2</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Move mouse on canvas element.</aside>

    <script src="../include/utils.js"></script>
    <script src="./classes/arrow.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          mouse = utils.captureMouse(canvas),
          arrow = new Arrow(),
          vx = 0,
          vy = 0,
          force = 0.05;

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        var dx = mouse.x - arrow.x,
            dy = mouse.y - arrow.y,
            angle = Math.atan2(dy, dx),
            ax = Math.cos(angle) * force,
            ay = Math.sin(angle) * force;

        arrow.rotation = angle;
        vx += ax;
        vy += ay;
        arrow.x += vx;
        arrow.y += vy;
        arrow.draw(context);
      }());
    };
    </script>
  </body>
</html>
View Code

4.太空船程序

经过前面知识的累积,不难理解下面的代码。

11-ship-sim.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Ship Sim</title>
    <link rel="stylesheet" href="../include/style.css">
    <style>
      #canvas {
        background-color: #000000;
      }
    </style>
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Press left and right arrow keys to rotate ship, up to add thrust.</aside>

    <script src="../include/utils.js"></script>
    <script src="./classes/ship.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          ship = new Ship(),
          vr = 0,
          vx = 0,
          vy = 0,
          thrust = 0;

      ship.x = canvas.width / 2;
      ship.y = canvas.height / 2;

      window.addEventListener('keydown', function (event) {
        switch (event.keyCode) {
        case 37:      //left
          vr = -3;
          break;
        case 39:      //right
          vr = 3;
          break;
        case 38:      //up
          thrust = 0.05;
          ship.showFlame = true;
          break;
        }
      }, false);

      window.addEventListener('keyup', function () {
        vr = 0;
        thrust = 0;
        ship.showFlame = false;
      }, false);

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        ship.rotation += vr * Math.PI / 180;
        var angle = ship.rotation, //in radians
            ax = Math.cos(angle) * thrust,
            ay = Math.sin(angle) * thrust;

        vx += ax;
        vy += ay;
        ship.x += vx;
        ship.y += vy;
        ship.draw(context);
      }());
    };
    </script>
  </body>
</html>
View Code

style.css

/* Some HTML5 Tags
 */

aside, footer, header, nav, section {
  display: block;
}

/* Examples
 */

body {
  background-color: #bbb;
  color: #383838;
}

#canvas {
  background-color: #fff;
}

header {
  padding-bottom: 10px;
}

header a {
  color: #30f;
  text-decoration: none;
}

aside {
  padding-top: 6px;
}

/* Index page
 */

#index-body {
  background-color: #fdeba1;
  font-family: "Vollkorn", serif;
  color: #000;
}

#index-body a {
  text-decoration: none;
  color: #b30300;
}

#index-body #description, #index-body #exercises {
  overflow: auto;
  max-width: 900px;
  margin: 0px auto 20px auto;
  padding-left: 15px;
  padding-bottom: 15px;
  background-color: #fff;
  border-radius: 15px;
}

#index-body #description {
  margin-top: 40px;
}

#index-body h1 {
  color: #b30300;
}

#index-body #description h2 {
  margin-bottom: 0;
}

#index-body h1 a {
  text-decoration: underline;
  color: #b30300;
}

#index-body li h2, #index-body li h3, #index-body li h4 {
  color: #000;
}

#index-body li h3 {
  margin-bottom: 0px;
}

#index-body #description ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

#index-body #description ul li {
 padding-bottom: 0.6em;
}
.container {
  display: table;
  width: 100%;
  height: auto;
}
.container .text {
    display:table-cell;
    height:100%;
    vertical-align:middle;
}
.container img {
  padding: 0 20px;
  display: block;
  float: right;
}
.container .clear {
  clear: both;
}

#exercises ul {
  margin: 0;
  padding: 4px 20px 10px 20px;
}

#exercises ol {
  margin: 0 20px 10px 0;
  padding: 0;
  list-style-type: none;
}

#exercises ol li {
  padding-top: 5px;
}

#exercises ol ol ol {
  padding-left: 60px;
  list-style-type: decimal-leading-zero;
}

#exercises ol ol ol li img, #exercises ol ol li img {
  margin-left: 4px;
  margin-bottom: -10;
}

#exercises h2 {
  margin: 10px 0 0 0;
}
View Code

utils.js

/**
 * Normalize the browser animation API across implementations. This requests
 * the browser to schedule a repaint of the window for the next animation frame.
 * Checks for cross-browser support, and, failing to find it, falls back to setTimeout.
 * @param {function}    callback  Function to call when it's time to update your animation for the next repaint.
 * @param {HTMLElement} element   Optional parameter specifying the element that visually bounds the entire animation.
 * @return {number} Animation frame request.
 */
if (!window.requestAnimationFrame) {
  window.requestAnimationFrame = (window.webkitRequestAnimationFrame ||
                                  window.mozRequestAnimationFrame ||
                                  window.msRequestAnimationFrame ||
                                  window.oRequestAnimationFrame ||
                                  function (callback) {
                                    return window.setTimeout(callback, 17 /*~ 1000/60*/);
                                  });
}

/**
 * ERRATA: 'cancelRequestAnimationFrame' renamed to 'cancelAnimationFrame' to reflect an update to the W3C Animation-Timing Spec.
 *
 * Cancels an animation frame request.
 * Checks for cross-browser support, falls back to clearTimeout.
 * @param {number}  Animation frame request.
 */
if (!window.cancelAnimationFrame) {
  window.cancelAnimationFrame = (window.cancelRequestAnimationFrame ||
                                 window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
                                 window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame ||
                                 window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame ||
                                 window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame ||
                                 window.clearTimeout);
}

/* Object that contains our utility functions.
 * Attached to the window object which acts as the global namespace.
 */
window.utils = {};

/**
 * Keeps track of the current mouse position, relative to an element.
 * @param {HTMLElement} element
 * @return {object} Contains properties: x, y, event
 */
window.utils.captureMouse = function (element) {
  var mouse = {x: 0, y: 0, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;
  
  element.addEventListener('mousemove', function (event) {
    var x, y;
    
    if (event.pageX || event.pageY) {
      x = event.pageX;
      y = event.pageY;
    } else {
      x = event.clientX + body_scrollLeft + element_scrollLeft;
      y = event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;
    
    mouse.x = x;
    mouse.y = y;
    mouse.event = event;
  }, false);
  
  return mouse;
};

/**
 * Keeps track of the current (first) touch position, relative to an element.
 * @param {HTMLElement} element
 * @return {object} Contains properties: x, y, isPressed, event
 */
window.utils.captureTouch = function (element) {
  var touch = {x: null, y: null, isPressed: false, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;

  element.addEventListener('touchstart', function (event) {
    touch.isPressed = true;
    touch.event = event;
  }, false);

  element.addEventListener('touchend', function (event) {
    touch.isPressed = false;
    touch.x = null;
    touch.y = null;
    touch.event = event;
  }, false);
  
  element.addEventListener('touchmove', function (event) {
    var x, y,
        touch_event = event.touches[0]; //first touch
    
    if (touch_event.pageX || touch_event.pageY) {
      x = touch_event.pageX;
      y = touch_event.pageY;
    } else {
      x = touch_event.clientX + body_scrollLeft + element_scrollLeft;
      y = touch_event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;
    
    touch.x = x;
    touch.y = y;
    touch.event = event;
  }, false);
  
  return touch;
};

/**
 * Returns a color in the format: '#RRGGBB', or as a hex number if specified.
 * @param {number|string} color
 * @param {boolean=}      toNumber=false  Return color as a hex number.
 * @return {string|number}
 */
window.utils.parseColor = function (color, toNumber) {
  if (toNumber === true) {
    if (typeof color === 'number') {
      return (color | 0); //chop off decimal
    }
    if (typeof color === 'string' && color[0] === '#') {
      color = color.slice(1);
    }
    return window.parseInt(color, 16);
  } else {
    if (typeof color === 'number') {
      color = '#' + ('00000' + (color | 0).toString(16)).substr(-6); //pad
    }
    return color;
  }
};

/**
 * Converts a color to the RGB string format: 'rgb(r,g,b)' or 'rgba(r,g,b,a)'
 * @param {number|string} color
 * @param {number}        alpha
 * @return {string}
 */
window.utils.colorToRGB = function (color, alpha) {
  //number in octal format or string prefixed with #
  if (typeof color === 'string' && color[0] === '#') {
    color = window.parseInt(color.slice(1), 16);
  }
  alpha = (alpha === undefined) ? 1 : alpha;
  //parse hex values
  var r = color >> 16 & 0xff,
      g = color >> 8 & 0xff,
      b = color & 0xff,
      a = (alpha < 0) ? 0 : ((alpha > 1) ? 1 : alpha);
  //only use 'rgba' if needed
  if (a === 1) {
    return "rgb("+ r +","+ g +","+ b +")";
  } else {
    return "rgba("+ r +","+ g +","+ b +","+ a +")";
  }
};

/**
 * Determine if a rectangle contains the coordinates (x,y) within it's boundaries.
 * @param {object}  rect  Object with properties: x, y, width, height.
 * @param {number}  x     Coordinate position x.
 * @param {number}  y     Coordinate position y.
 * @return {boolean}
 */
window.utils.containsPoint = function (rect, x, y) {
  return !(x < rect.x ||
           x > rect.x + rect.width ||
           y < rect.y ||
           y > rect.y + rect.height);
};

/**
 * Determine if two rectangles overlap.
 * @param {object}  rectA Object with properties: x, y, width, height.
 * @param {object}  rectB Object with properties: x, y, width, height.
 * @return {boolean}
 */
window.utils.intersects = function (rectA, rectB) {
  return !(rectA.x + rectA.width < rectB.x ||
           rectB.x + rectB.width < rectA.x ||
           rectA.y + rectA.height < rectB.y ||
           rectB.y + rectB.height < rectA.y);
};
View Code

ship.js

function Ship () {
  this.x = 0;
  this.y = 0;
  this.width = 25;
  this.height = 20;
  this.rotation = 0;
  this.showFlame = false;
}

Ship.prototype.draw = function (context) {
  context.save();
  context.translate(this.x, this.y);
  context.rotate(this.rotation);
  
  context.lineWidth = 1;
  context.strokeStyle = "#ffffff";
  context.beginPath();
  context.moveTo(10, 0);
  context.lineTo(-10, 10);
  context.lineTo(-5, 0);
  context.lineTo(-10, -10);
  context.lineTo(10, 0);
  context.stroke();

  if (this.showFlame) {
    context.beginPath();
    context.moveTo(-7.5, -5);
    context.lineTo(-15, 0);
    context.lineTo(-7.5, 5);
    context.stroke();
  }
  context.restore();
};
View Code

 

posted on 2015-01-27 16:57  吹过的风  阅读(916)  评论(0编辑  收藏  举报