用CANVAS画布制作随机小球

不多说先上图在这里插入图片描述

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#myCanvas{
				border: 1px solid black;
				margin: 20px auto;
				display:block;
			}
		</style>
	</head>
	<body>
		<!--canvas:"画布",使用来绘制图形的,最终以图片的形式显示在浏览器上,默认宽高300/150-->
	
		<canvas id="myCanvas" width="600" height="600">
			当前浏览器不支持canvas---不兼容
		</canvas>
		
	</body>
	<script type="text/javascript">
		var canvas=document.getElementById("myCanvas");
        var pencil=canvas.getContext("2d");
        function random(m,n){
        	return Math.floor(Math.random()*(n-m+1)+m);
        }
		function Ball(){
			//设置属性
			//随机小球的半径
			this.r = random(5,10);
			//随机小球的颜色
			this.color = "rgb("+random(0,255)+","+random(0,255)+","+random(0,255)+")";
			//随机小球圆心x,圆心y
			this.x = random(this.r,canvas.width-this.r);//保证小球不出去
			this.y = random(this.r,canvas.height-this.r);
			//随机速度(控制移动方向)
			//水平方向上的速度    一半几率  random(0,1) ? 1:-1     (random(1,10) >= 5 ? 1 : -1)
			this.speedX = random(2,6)*(random(0,1)?1:-1);
			//垂直方向上的速度
			this.speedY = random(2,6)*(random(0,1)?1:-1);
		}
			Ball.prototype.move = function(){
				//
				this.x += this.speedX;
				this.y += this.speedY;
				//小球碰撞四个边界反弹
				//左边界
				if(this.x <= this.r){
					this.x = this.r;
					//反弹
					this.speedX *= -1;
				}
				//右边界
				if(this.x >= canvas.width - this.r){
					this.x =canvas.width - this.r ;
					//反弹
					this.speedX *= -1;
				}
				//上边界
				if(this.y <= this.r){
					this.y = this.r;
					//反弹
					this.speedY *= -1;
				}
				//下边界
				if(this.y >= canvas.height- this.r){
					this.y =canvas.height - this.r ;
					//反弹
					this.speedY *= -1;	
				}
			}
			//绘制小球的方法
			Ball.prototype.draw = function(){
				//开始绘制
				pencil.beginPath();
				pencil.arc(this.x,this.y,this.r,0,Math.PI*2,false);
			//填充
				pencil.fillStyle = this.color;
				pencil.fill();
			}
			var balls = [];//存储所有的小球对象
			//创建对象
			for(var i = 0;i < 100;i++){
				var ball = new Ball();
				balls.push(ball);
			}
			pencil.shadowColor = "lightcyan";
				pencil.shadowBlur = 30;
			//让小球移动起来
			setInterval(function(){
				//每次小球重新绘制和移动移动之前,清空画布中的内容
				pencil.clearRect(0,0,canvas.width,canvas.height); 				
				pencil.beginPath();
				pencil.fillStyle = "black";
				pencil.fillRect(0,0,canvas.width,canvas.height);
				for(var i=0;i<balls.length;i++){
					balls[i].draw();//绘制小球
					balls[i].move();//移动小球
				}
			},20)
			
	</script>
</html>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值