<!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>
canvas学习笔记(一):弹跳的小球
猜你喜欢
转载自blog.csdn.net/qq_36514197/article/details/120269075
今日推荐
周排行