canvas 无规则小球碰撞
1、利用canvas制造不同大小、随机颜色、随机速度 的无规则小球碰撞,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>不同颜色大小的小球碰撞效果</title>
</head>
<style type="text/css">
#myCanvas {
border: 1px solid #000000;
}
</style>
<body>
<canvas id="myCanvas" width="500" height="500">浏览器不支持Canvas</canvas>
</body>
</html>
<script type="text/javascript">
var car = document.getElementById("myCanvas");
var ctx = car.getContext("2d");
var h = 500;
var w = 500;
//产生随机值
function rNumber(num) {
return Math.random() * num;
}
function Bobble() {
//起始点x
this.x = rNumber(400) + 50; //(50,450)
//起始点y
this.y = rNumber(400) + 50; //(50,450)
//半径
this.r = rNumber(40) + 10; //(10,50)
//小球运动速度(X方向)
this.speedX = rNumber(4) + 2; //(2,6)
//小球运动速度(Y方向)
this.speedY = rNumber(4) + 2; //(2,6)
//随机颜色
this.color = randomHexColor();
}
// show() : 创造小球
Bobble.prototype.show = function() {
motion(this.x, this.y, this.r, this.color)
}
// run() : 小球运动
Bobble.prototype.run = function() {
//改变X的坐标
this.x = this.x + this.speedX;
//当x的位置加上半径大于等于总宽度的时候,代表小球刚好与右边边框相碰
//当x的位置加上半径小于等于0的时候,代表小球刚好与左边边框相碰
if (this.r + this.x >= w || this.x - this.r <= 0) {
//当判断成立时,代表速度要取相反值,小球才会进行反方向运动
this.speedX = -this.speedX;
}
//Y方向的位置变化规律同X方向的位置变化一样
this.y = this.y + this.speedY;
if (this.r + this.y >= h || this.y - this.r <= 0) {
this.speedY = -this.speedY;
}
}
//创建完小球后,把对应小球的对象储存起来
var newData = [];
//制造100个小球,这里可以修改成你想要的数量
for (var i = 0; i < 100; i++) {
var bobble = new Bobble();
//添加小球对象
newData.push(bobble);
//创建小球
bobble.show();
}
setInterval(() => {
//清除内容
ctx.clearRect(0, 0, w, h);
for (var i = 0; i < newData.length; i++) {
var ball = newData[i];
//小球运动
ball.run();
//小球产生新的位置
ball.show()
}
}, 10)
//创建小球的方法
function motion(x, y, r, color) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.strokeStyle = color;
ctx.stroke();
ctx.closePath();
}
//随机生成十六进制颜色
function randomHexColor() {
//生成ffffff以内16进制数
var hex = Math.floor(Math.random() * 16777216).toString(16);
//while循环判断hex位数,少于6位前面加0凑够6位
while (hex.length < 6) {
hex = '0' + hex;
}
//返回‘#'开头16进制颜色
return '#' + hex;
}
</script>

浙公网安备 33010602011771号