书籍名称:HTML5-Animation-with-JavaScript
书籍源码:https://github.com/lamberta/html5-animation
1.脉动是一种半径r来回反复的运动,在canvas中他是对原图形的方法和缩小。可以将sin应用在控制大小的属性scaleX,scaleY。
以下代码在先前的实例中对index.html的进行修改即可。
index.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Pulse</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(), angle = 0, centerScale = 1, range = 0.5, speed = 0.05; ball.x = canvas.width / 2; ball.y = canvas.height / 2; (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); //利用正弦设置放大的倍数 ball.scaleX = ball.scaleY = centerScale + Math.sin(angle) * range; angle += speed; ball.draw(context); }()); }; </script> </body> </html>
2.对球体的位置x,y分别用一个sin函数来表示,且角度递增的速度不一样,可以实现无规则运动,代码如下
仍然只是index.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Random</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(), angleX = 0, angleY = 0, range = 50, centerX = canvas.width / 2, centerY = canvas.height / 2, xspeed = 0.07, yspeed = 0.11; (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); ball.x = centerX + Math.sin(angleX) * range; ball.y = centerY + Math.sin(angleY) * range; angleX += xspeed; angleY += yspeed; ball.draw(context); }()); }; </script> </body> </html>