1、圆球跳动的动画
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>圆球跳动的动画</title>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script type="text/javascript">
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
//记住圆球的状态
var ball={
x:10,
y:100,
dir_x:5,
dir_y:5
};
//动画
setInterval(drawBall,50);
function drawBall(){
//绘制背景
ctx.fillStyle="#ccc";
ctx.fillRect(0,0,300,300);
//绘制圆球
ctx.beginPath();
ctx.arc(ball.x,ball.y,7,0,2*Math.PI,true);
ctx.fillStyle="red";
ctx.fill();
//让圆球运动起来
ball.x += ball.dir_x;
ball.y += ball.dir_y;
if(ball.x<0 || ball.x>300){ball.dir_x*=-1;}
if(ball.y<0 || ball.y>300){ball.dir_y*=-1;}
}
</script>
</body>
</html>
2、待机动画
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>待机动画</title>
<style type="text/css">
#canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script type="text/javascript">
var ctx=document.getElementById("canvas").getContext("2d");
//动画绘制开始
var ci=0;
anim();
//定义动画函数
function anim(){
//清空canvas
ctx.clearRect(0,0,300,300);
//循环绘制36根长方形棒棒
for(var i=0;i<36;i++){
ctx.save();
//旋转
var r=(i*10)*Math.PI/180;
//移动中心点
ctx.translate(150,150);
ctx.rotate(r);
//绘制细长方形
if(i==ci){
ctx.globalAlpha=0.7;//透明度
}else{
ctx.globalAlpha=0.45;//透明度
}
ctx.beginPath();
ctx.fillStyle="gray";
ctx.rect(0,0,50,6);
ctx.fill();
ctx.restore();
}
ci=(ci+1)%36;
//每隔一定时间调用函数本身,实现动画效果
setTimeout(anim,20);
}
</script>
</body>
</html>