Canvas实现矩形随机铺满的动画效果

这篇博客介绍了如何利用HTML5的Canvas API重写一个矩形随机铺满的动画效果,提供了源代码和注释,读者可以直接保存为HTML文件查看动画演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原作地址:http://codepen.io/svendsen/pen/eNjqar

效果如下:


本人将其源代码重写后并添加注释,直接复制保存为HTML即可看到效果。

源码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style type="text/css">
    	body {
    		text-align: center;
    		background-color: #2c3e50;
    	}
    	canvas {
    		border: 20px solid black;
    	}
    </style>
</head>

<body>
    <canvas id="canvas" width="600" height="600"></canvas>
    <script src="js/jquery-1.11.3.js"></script>
    <script type="text/javascript">
    	//获取min至max间的随机数
		function getRandom(min, max) {
			return Math.random() * (max - min) + min;
		}

		//获取16进制的随机颜色
		function getRandomColor() {
			var colors = '0123456789ABCEDF'.split('');
			// console.log(colors);
			var color = '#';
			for (var i = 0; i < 6; i++) {
				color += colors[Math.floor(Math.random() * 16)];
			}
			return color;
		}

		//正方形构造器,x和y是开始绘制正方形的坐标,size是边长
		function Rect() {
			this.x = 400;
			this.y = 400;
			this.size = 400;
		}

		//正方形的自变化方法
		Rect.prototype.move = function() {
			//利用随机数改变矩形的初始位置坐标和边长
			this.x = this.x + getRandom(-60, 60);
			this.y = this.y + getRandom(-60, 60);
			this.size = this.size + getRandom(-50, 50);

			//超界修正
			if (this.x < 10) { this.x = 10; }
			if (this.y < 10) { this.y = 10; }
			if ( (this.x + this.size) > 600 ) { this.x = 600 - this.size; }
			if ( (this.y + this.size) > 600 ) { this.y = 600 - this.size; }

			if (this.size < 0) { this.size = 0; }
			if (this.size > 200) { this.size = 200; }
		};

		//根据传入的矩形对象绘制图形
		function render(rect, ctx) {
			rect.move();
			ctx.fillStyle = getRandomColor();
			ctx.fillRect(rect.x, rect.y, rect.size, rect.size);
		}

		//获取矩形对象,获取canvas上下文
		var rect = new Rect();
		var c = document.getElementById('canvas');
		var ctx = c.getContext('2d');

		//间隔执行绘图方法
		setInterval(function() {
			render(rect, ctx);
		}, 50);
    </script>
</body>
<html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值