首页 > 代码库 > canvas简单动画

canvas简单动画

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
canvas{
border: 1px solid #AAAAAA;
}
</style>
</head>
<body>
<canvas id="can" width="500" height="400"></canvas>
<script type="text/javascript">
var ctx=can.getContext(‘2d‘)
ctx.fillStyle=‘#0a0‘
ctx.fillRect(0,0,100,80)
var y=1;
var yd=1;
var i=1;
var xd=1;//前进还是后退 1 -1
setInterval(function(){

ctx.clearRect(0,0,500,400)
ctx.fillRect(i,y,100,80)
y+=yd*2;
if(y>320){
yd=-1
}else if(y<=0){
yd=1
}
i+=xd*2;
if(i>400){
xd=-1
}else if(i<=0){
xd=1
}



},10)

</script>
</body>
</html>

canvas简单动画