canvas学习笔记(一):弹跳的小球

在这里插入图片描述

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
</head>
<body>

<canvas id="cont" width="500" height="500">您的浏览器版本过低!</canvas>

<script>
	
	/* 固定-start */
	var canvas = document.querySelector("#cont");
	var ctx = canvas.getContext("2d");
	
	// 画布宽高
	var w = 500,
		h = 500;
	
	function r(num) {
		return Math.random() * num;
	}
	
	// 随机小球对象
	function randomBall() {
		this.r = r(40) + 10; //[10, 50);
		this.x = r(5) + 50;
		this.y = r(3) + 50;
		this.color = '#' + Math.random().toString(16).substr(2, 6).toUpperCase();
	
		this.xSpeed = r(3) + 2; //[2, 5)
		this.ySpeed = r(3) + 1; //[1, 4)	
	};
	
	// 展示小球方法
	randomBall.prototype.show = function() {
		ctx.beginPath();
		ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
		ctx.fillStyle = this.color;
		ctx.fill();
	};
	
	// 小球运动方法
	randomBall.prototype.run = function() {
		if (this.x <= this.r || this.x + this.r >= w) {
			this.xSpeed = -this.xSpeed;
		}
		if (this.y <= this.r || this.y + this.r >= h) {
			this.ySpeed = -this.ySpeed;
		}
		this.x += this.xSpeed;
		this.y += this.ySpeed;
	}
	
	// 创造小球
	var ballArr = [];
	for (var i = 0; i <= 10; i++) {
		var ball = new randomBall();
		ballArr.push(ball);
	}
	
	// 定时器
	setInterval(function() {
		// 每次都先清除画布
		ctx.clearRect(0, 0, w, h);
		for (var i = 0; i < ballArr.length; i++) {
			var ball = ballArr[i];
			ball.run();
			ball.show();
		}
	}, 10);
	
</script>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_tt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值