小编以一个运动的小车为例子,讲述了三种实现HTML5动画的方式,思路清晰,动画不仅仅是canvas,还有css3和javascript.通过合理的选择,来实现最优的实现。
PS:由于显卡、录制的帧间隔,以及可能你电脑处理器的原因,播放过程可能有些不太流畅或者失真!
分三种方式实现:
(1) canvas元素结合JS
(2) 纯粹的CSS3动画(暂不被所有主流浏览器支持,比如IE)
(3) CSS3结合Jquery实现
知道如何使用CSS3动画比知道如何使用<canvas>元素更重要:因为浏览器能够优化那些元素的性能(通常是他们的样式,比如CSS),而我们使用canvas自定义画出来的效果却不能被优化。原因又在于,浏览器使用的硬件主要取决于显卡的能力。目前,浏览器没有给予我们直接访问显卡的权力,比如,每一个绘画操作都不得不在浏览器中先调用某些函数。
1.canvas
html代码:
<html>
<head>
<meta charset="UTF-8" />
<title>Animation in HTML5 using the canvas element</title>
</head>
<body onload="init();">
<canvas id="canvas" width="1000" height="600">Your browser does not support the <code><canvas></code>-element.Please think about updating your brower!</canvas>
<div id="controls">
<button type="button" onclick="speed(-0.1);">Slower</button>
<button type="button" onclick="play(this);">Play</button>
<button type="button" onclick="speed(+0.1)">Faster</button>
</div>
</body>
</html>
js代码:
定义一些变量:
var dx=5, //当前速率
rate=1, //当前播放速度
ani, //当前动画循环
c, //画图(Canvas Context)
w, //汽车[隐藏的](Canvas Context)
grassHeight=130, //背景高度
carAlpha=0, //轮胎的旋转角度
carX=-400, //x轴方向上汽车的位置(将被改变)
carY=300, //y轴方向上汽车的位置(将保持为常量)
carWidth=400, //汽车的宽度
carHeight=130, //汽车的高度
tiresDelta=15, //从一个轮胎到最接近的汽车底盘的距离
axisDelta=20, //汽车底部底盘的轴与轮胎的距离
radius=60; //轮胎的半径
为了实例化汽车canvas(初始时被隐藏),我们使用下面的自执行的匿名函数
(function(){
var car=document.createElement('canvas'); //创建元素
car.height=carHeight+axisDelta+radius; //设置高度
car.width=carWidth; //设置宽度
w=car.getContext('2d');
})();
点击“Play”按钮,通过定时重复执行“画汽车”操作,来模拟“帧播放”功能: