代码
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="utf-8">
<title
></title
>
<style
>
#canvas
{
border
: 1px solid red
;
}
</style
>
</head
>
<body
>
<canvas id
="canvas" width
="500px" height
="400px">
</canvas
>
</body
>
<script type
="text/javascript">
var cas
=document
.getElementById("canvas");
var ctx
=cas
.getContext("2d");
var img
=new Image();
img
.src
="rabbit.png";
img
.onload=function(){
}
var x
=cas
.width
/2;
var speed
=-3;
var rowIndex
=0;
var colIndex
=1;
setInterval(function(){
x
+=speed
;
if(x
>cas
.width
-40)
{
speed
=-speed
;
colIndex
=1;
}
else if(x
<0)
{
speed
=-speed
;
colIndex
=2;
}
if(rowIndex
>=3)
{
rowIndex
=0;
}else{
rowIndex
++;
}
ctx
.clearRect(0,0,cas
.width
,cas
.height
);
ctx
.drawImage(img
,rowIndex
*40,colIndex
*65,40,65,x
,cas
.height
/2-32.5,40,65);
},100)
</script
>
</html
>
效果
原理
原理 :
一小段一小段的图相当于按帧播放,形成一个拼出动图
转载请注明原文地址:https://tech.qufami.com/read-19310.html