配合使用JavaScript中提供的requestAnimationFrame方法,可以很容易的在canvas中实现动画效果
一般来说,需要按照下面的步骤来创建动画:
1. 清空canvas:使用clearRect方法,清空区域。 2. 保存canvas状态:如果你要改变一些会改变canvas状态的设置(样式,变形之类的),又要在每画一帧之时都是原始状态的话,你需要先保存一下。 3. 绘制动画图形(animated shapes) 4. 恢复canvas状态
GridFunny定义与Canvas概述一节中一致
window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( /* function */ callback, /* DOMElement */ element) { window.setTimeout(callback, 1000 / 60); }; })(); var grid = new GridFunny({ nextDraw: function() { var time = new Date().getTime() * 0.002, num = this.settings.gridNum, canvasSize = this.settings.canvasSize, cX = canvasSize.width / 2, cY = canvasSize.height / 2, x = Math.sin(time) * this.pixelX + cX, y = Math.cos(time * 0.9) * this.pixelY + cY, gradient = this.context.createRadialGradient(x, y, 20, cX, cY, 110); gradient.addColorStop(0, 'yellow'); gradient.addColorStop(1, 'green'); this.context.fillStyle = gradient; this.context.beginPath(); this.context.arc(cX, cY, 110, 0, 2 * Math.PI, false); this.context.fill(); this.context.closePath(); } }); grid.start(); var animate = function() { requestAnimationFrame(animate); grid._drawBoard(); }; animate();
代码的执行效果如下: