书籍名称:HTML5-Animation-with-JavaScript
书籍源码:https://github.com/lamberta/html5-animation1
1.两个物体
和判断鼠标是否在物体内相似,额外要多考虑鼠标方物体的半径。这不是准确的碰撞,它是假设物体在正方形基础上的简易方法。
01-object-hit-test.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Object Hit Test</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> <textarea id="log"></textarea> <aside>Drag circle with mouse.</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'), log = document.getElementById('log'), mouse = utils.captureMouse(canvas), ballA = new Ball(), ballB = new Ball(); ballA.x = canvas.width / 2; ballA.y = canvas.height / 2; (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); ballB.x = mouse.x; ballB.y = mouse.y; if (utils.intersects(ballA.getBounds(), ballB.getBounds())) { log.value = "Hit!"; } else { log.value = ''; } ballA.draw(context); ballB.draw(context); //draw bounding boxes var boundsA = ballA.getBounds(), boundsB = ballB.getBounds(); context.strokeRect(boundsA.x, boundsA.y, boundsA.width, boundsA.height); context.strokeRect(boundsB.x, boundsB.y, boundsB.width, boundsB.height); }()); }; </script> </body> </html>
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); };
物体堆叠
关键点是判断新生成的矩形与之前所有的矩形判断是否碰撞,然后决定这个矩形的y位置。
02-boxes.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Boxes</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/box.js"></script> <script> window.onload = function () { var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), boxes = [], activeBox = createBox(), gravity = 0.2; function createBox () { var box = new Box(Math.random() * 40 + 10, Math.random() * 40 + 10); box.x = Math.random() * canvas.width; boxes.push(box); return box; } function drawBox (box) { if (activeBox !== box && utils.intersects(activeBox, box)) { activeBox.y = box.y - activeBox.height; activeBox = createBox(); } box.draw(context); } (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); activeBox.vy += gravity; activeBox.y += activeBox.vy; if (activeBox.y + activeBox.height > canvas.height) { activeBox.y = canvas.height - activeBox.height; activeBox = createBox(); } boxes.forEach(drawBox); }()); }; </script> </body> </html>
两个圆之间的碰撞
两个圆之间碰撞可以用圆心的距离小于两个原的半径合。
04-distance-1.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Distance 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> <textarea id="log"></textarea> <aside>Drag circle with mouse.</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'), mouse = utils.captureMouse(canvas), log = document.getElementById('log'), ballA = new Ball(30), ballB = new Ball(30); ballA.x = canvas.width / 2; ballA.y = canvas.height / 2; canvas.addEventListener('mousemove', drawFrame, false); drawFrame(); function drawFrame () { context.clearRect(0, 0, canvas.width, canvas.height); ballB.x = mouse.x; ballB.y = mouse.y; var dx = ballB.x - ballA.x, dy = ballB.y - ballA.y, dist = Math.sqrt(dx * dx + dy * dy); if (dist < 60) { log.value = "Hit!"; } else { log.value = ''; } ballA.draw(context); ballB.draw(context); } }; </script> </body> </html>
碰撞和反弹
06-bubbles-1.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Bubbles 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'), centerBall = new Ball(100, "#cccccc"), balls = [], numBalls = 10, spring = 0.03, bounce = -1; centerBall.x = canvas.width / 2; centerBall.y = canvas.height / 2; for (var ball, i = 0; i < numBalls; i++) { ball = new Ball(Math.random() * 40 + 5, Math.random() * 0xffffff); ball.x = Math.random() * canvas.width / 2; ball.y = Math.random() * canvas.height / 2; ball.vx = Math.random() * 6 - 3; ball.vy = Math.random() * 6 - 3; balls.push(ball); } function move (ball) { ball.x += ball.vx; ball.y += ball.vy; if (ball.x + ball.radius > canvas.width) { ball.x = canvas.width - ball.radius; ball.vx *= bounce; } else if (ball.x - ball.radius < 0) { ball.x = ball.radius; ball.vx *= bounce; } if (ball.y + ball.radius > canvas.height) { ball.y = canvas.height - ball.radius; ball.vy *= bounce; } else if (ball.y - ball.radius < 0) { ball.y = ball.radius; ball.vy *= bounce; } } function draw (ball) { var dx = ball.x - centerBall.x, dy = ball.y - centerBall.y, dist = Math.sqrt(dx * dx + dy * dy), min_dist = ball.radius + centerBall.radius; if (dist < min_dist) { var angle = Math.atan2(dy, dx), tx = centerBall.x + Math.cos(angle) * min_dist, ty = centerBall.y + Math.sin(angle) * min_dist; ball.vx += (tx - ball.x) * spring; ball.vy += (ty - ball.y) * spring; } ball.draw(context); } (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); balls.forEach(move); balls.forEach(draw); centerBall.draw(context); }()); }; </script> </body> </html>
多重对象
07-bubbles-2.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Bubbles 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> <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'), balls = [], numBalls = 10, bounce = -0.5, spring = 0.03, gravity = 0.1; for (var ball, i = 0; i < numBalls; i++) { ball = new Ball(Math.random() * 30 + 20, Math.random() * 0xffffff); ball.x = Math.random() * canvas.width / 2; ball.y = Math.random() * canvas.height / 2; ball.vx = Math.random() * 6 - 3; ball.vy = Math.random() * 6 - 3; balls.push(ball); } function checkCollision (ballA, i) { for (var ballB, dx, dy, dist, min_dist, j = i + 1; j < numBalls; j++) { ballB = balls[j]; dx = ballB.x - ballA.x; dy = ballB.y - ballA.y; dist = Math.sqrt(dx * dx + dy * dy); min_dist = ballA.radius + ballB.radius; if (dist < min_dist) { var angle = Math.atan2(dy, dx), tx = ballA.x + Math.cos(angle) * min_dist, ty = ballA.y + Math.sin(angle) * min_dist, ax = (tx - ballB.x) * spring * 0.5, //multiply by half a spring ay = (ty - ballB.y) * spring * 0.5; ballA.vx -= ax; ballA.vy -= ay; ballB.vx += ax; ballB.vy += ay; } } } function move (ball) { ball.vy += gravity; ball.x += ball.vx; ball.y += ball.vy; if (ball.x + ball.radius > canvas.width) { ball.x = canvas.width - ball.radius; ball.vx *= bounce; } else if (ball.x - ball.radius < 0) { ball.x = ball.radius; ball.vx *= bounce; } if (ball.y + ball.radius > canvas.height) { ball.y = canvas.height - ball.radius; ball.vy *= bounce; } else if (ball.y - ball.radius < 0) { ball.y = ball.radius; ball.vy *= bounce; } } function draw (ball) { ball.draw(context); } (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); balls.forEach(checkCollision); balls.forEach(move); balls.forEach(draw); }()); }; </script> </body> </html>
嵌套迭代
08-bubbles-3.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Bubbles 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> <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'), balls = [], numBalls = 10, bounce = -0.5, spring = 0.015, gravity = 0.1; for (var ball, i = 0; i < numBalls; i++) { ball = new Ball(Math.random() * 30 + 20, Math.random() * 0xffffff); ball.x = Math.random() * canvas.width / 2; ball.y = Math.random() * canvas.height / 2; ball.vx = Math.random() * 6 - 3; ball.vy = Math.random() * 6 - 3; balls.push(ball); } function checkCollision (ballA, i) { for (var ballB, dx, dy, dist, min_dist, j = i + 1; j < numBalls; j++) { ballB = balls[j]; dx = ballB.x - ballA.x; dy = ballB.y - ballA.y; dist = Math.sqrt(dx * dx + dy * dy); min_dist = ballA.radius + ballB.radius; if (dist < min_dist) { var tx = ballA.x + dx / dist * min_dist, ty = ballA.y + dy / dist * min_dist, ax = (tx - ballB.x) * spring, ay = (ty - ballB.y) * spring; ballA.vx -= ax; ballA.vy -= ay; ballB.vx += ax; ballB.vy += ay; } } } function move (ball) { ball.vy += gravity; ball.x += ball.vx; ball.y += ball.vy; if (ball.x + ball.radius > canvas.width) { ball.x = canvas.width - ball.radius; ball.vx *= bounce; } else if (ball.x - ball.radius < 0) { ball.x = ball.radius; ball.vx *= bounce; } if (ball.y + ball.radius > canvas.height) { ball.y = canvas.height - ball.radius; ball.vy *= bounce; } else if (ball.y - ball.radius < 0) { ball.y = ball.radius; ball.vy *= bounce; } } function draw (ball) { ball.draw(context); } (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); balls.forEach(checkCollision); balls.forEach(move); balls.forEach(draw); }()); }; </script> </body> </html>