小球的构造函数如下:
// 圆球的构造函数 function Ball(radius, color) { if(radius === undefined) { radius = 40; } if(color === undefined) { color = "#ff0000"; } this.x = 0; this.y = 0; this.radius = radius; this.rotation = 0; this.scaleX = 1; this.scaleY = 1; this.color = color; this.lineWidth = 1; } Ball.prototype.draw = function(context) { context.save(); context.translate(this.x, this.y); context.rotate(this.rotation); context.scale(this.scaleX, this.scaleY); context.lineWidth = this.lineWidth; context.fillStyle = this.color; context.beginPath(); context.arc(0, 0, this.radius, 0, Math.PI * 2, true); context.closePath(); context.fill(); if(this.lineWidth > 0) { context.stroke(); } context.restore(); }
正弦波的实现可以使用正弦函数 Math.sin(angle)
绘制。其中, angle值作为变量并递增时,即可使物体按正弦曲线运动,从而实现正弦波动画 。
过程如下:
(function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); ball.y = Math.sin(angle) * range; angle += speed; ball.draw(context); })();
可以在控制台中输出以下代码,了解下正弦波的数值分布:
var fullRadians = Math.PI * 2; for(var angle = 0; angle < fullRadians; angle += 0.01) { console.log(Math.sin(angle)); }
代码:
<canvas id="canvas" width="400" height="400" style="background: #ccc;"></canvas> window.onload = function() { var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), ball = new Ball(2), angle = 0, range = 50, speed = 0.1, isFoward = true; ball.x = 0; ball.y = canvas.height / 2; ball.lineWidth = 0; (function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); // context.clearRect(0, 0, canvas.width, canvas.height); ball.y = canvas.height / 2 + Math.sin(angle) * 100; if(isFoward) { ball.x += speed * 20; } else { ball.x -= speed * 20; } if(ball.x > canvas.width) { isFoward = false; context.clearRect(0, 0, canvas.width, canvas.height); } else if(ball.x < 0) { isFoward = true; context.clearRect(0, 0, canvas.width, canvas.height); } angle += speed; ball.draw(context); })(); };
演示如下: http://codepen.io/dengzhirong/pen/xOZypy
创建正弦波的方法,就是使用正弦函数 Math.sin(angle)
求值,并让弧度值angle根据运动时间递增。
创建正弦波的公式如下:
/** * range:正选的波峰值 * center:y轴的交点 * speed:正弦波的运动速度 * angle:弧度值,递增的变量 */ (function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); valeue = center + Math.sin(angle) * range; angle += speed; })();