Canvas画布实现动画效果

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>

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值