示例1,跟随鼠标的键头:

 
需要掌握一个重要的公式,这个方法返回从 x 轴到点 (x,y) 之间的角度
Math.atan2(dy,dx);

Canvas学习笔记——动画中的三角学-LMLPHP

关键代码:

 function Arrow() {
this.x = 0;
this.y = 0;
this.rotate = 0;
this.color = '#ffff00';
} Arrow.prototype.draw = function(context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotate);
context.fillStyle = this.color;
context.lineWidth = 2; context.beginPath();
context.moveTo( - 50, -25);
context.lineTo(0, -25);
context.lineTo(0, -50);
context.lineTo(50, 0);
context.lineTo(0, 50);
context.lineTo(0, 25);
context.lineTo( - 50, 25);
context.closePath(); context.fill();
context.stroke();
context.restore();
}; var canvas = document.getElementById('c'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
arrow = new Arrow(); arrow.x = canvas.width / 2;
arrow.y = canvas.height / 2; (function draw() {
window.requestAnimFrame(draw, canvas);
context.clearRect(0, 0, canvas.width, canvas.height); var dx = mouse.x - arrow.x,
dy = mouse.y - arrow.y,
rotate = Math.atan2(dy, dx); arrow.rotate = rotate; arrow.draw(context);
})();

示例2,平滑运动:

关键代码

yPos = centerY + Math.sin(angle) * range;
angle += 0.1;

示例3,脉冲运动:

需要注意,这里不需要清除画布,并且在开始绘制时应该使用beginPath()

 

示例4,圆周运动:

 
 

//

圆周运动的要点是用正弦来计算x坐标,余弦来算y坐标,椭圆则是x轴的运动和y轴的半径不同。

05-11 17:13