原作地址: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>