HTML5 Canvas动画效果演示
首先要准备一张有连续帧的图片,然后利用HTML5 Canvas的draw方法在不同的时间间隔绘制不同的帧,这样看起来就像动画在播放。
<div id="cantainer">准备四个按钮,分别是:左、右、上、下。
<canvas id="cavsElem">
</canvas>
</div>
<button id="btn-dir-left">←</button>
<button id="btn-dir-right">→</button>
<button id="btn-dir-up">↑</button>
<button id="btn-dir-down">↓</button>
<script>
(function(){
var canvas = document.querySelector("#cavsElem");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 400;
canvas.style.border = "1px solid #000";
var dirIndex = 0;
var img = new Image();
img.src = "imgs/gameImgs/DMMban.png";
img.onload = function(){
var frameIndex = 0;
setInterval(function(){
//清楚之前的 图片墨迹
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(
img
,frameIndex * 40 //获取原始图片的x坐标
,dirIndex * 65 //获取原始图片的y坐标
,40
,65
,200
,200
,80
,130
);
frameIndex++;//添加到下一帧
frameIndex %= 4;//0%4=0;1%4=1;2%4=2;3%4=3;4%4=0
}, 1000 / 10);
};
//绑定点击按钮事件
var btnLeft = document.getElementById("btn-dir-left");
btnLeft.onclick = function(){
//朝左跑
dirIndex = 1;
};
var btnRight = document.getElementById("btn-dir-right");
btnRight.onclick = function(){
//朝右跑
dirIndex = 2;
};
var btnUp = document.getElementById("btn-dir-up");
btnUp.onclick = function(){
//朝上跑
dirIndex = 3;
};
var btnDown = document.getElementById("btn-dir-down");
btnDown.onclick = function(){
//朝下跑
dirIndex = 0;
};
}());
</script>