Canvas画布之实现百球大战

这一次我们来实现一个百球大战的效果,一百个球在canavs画布中来回弹跳,是不是觉得非常有趣呢,
相信各位已经迫不及待想看它是怎么实现的吧!话不多说,开始吧。

Quick Start

Create a new html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>百球大战</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<canvas id="canvas">
您的浏览器不支持canvas,请更换主流浏览器
</canvas>
</body>
<script src="index.js></script>
</html>

Create a new index.css

1
2
3
4
5
6
7
8
9
*{
margin:0;
padding:0;
}
#canvas{
display: block;
margin:0 auto;
border:1px red solid;
}

Create a new index.js

这里才是这段程序的难点,这里我们采用构造函数的方式来编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var canvas = document.querySelector("#canvas");
canvas.width = 800;
canvas.height = 600;
var onOff = false;
var ctx = canvas.getContext("2d");
function Arc(){
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.speedX = speedX;
this.speedY = speedY;
}
Arc.prototype.drawArc = function(){
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x,this.y,this.r,0,Math.PI*2)
ctx.fill();
ctx.closePath();
ctx.restore();
}
Arc.prototype.move = function(){
if(this.x+this.speedX+this.r > canvas.width || this.x+this.speedX-this.r < 0){
this.speedX = -this.speedX;
}
if(this.y+this.speedY+this.r > canvas.height || this.y+this.speedY-this.r < 0){
this.speedY = - this.speedY;
}
this.x += this.speedX;
this.y += this.speedY;
}
var arr = [];
for(var i = 0;i<100;i++){
var x = random(50,750);
var y = random(50,550);
var r = random(10,30);
var speedX = random(3,10);
var speedY = random(3,10);
//ES6写法
var color = `rgb(${random(0,255)},${random(0,255)},${random(0,255)})`;
// ES5写法 var color = "rgb("+random(0,255)+","+random(0,255)+","+random(0,255)+")";
var obj = new Arc(x,y,r,color,speedX,speedY)
arr.push(obj);
}
var timer = null;
function ani(){
ctx.clearRect(0,0,canvas.width,canvas.height)
for(var i = 0;i<arr.length;i++){
arr[i].drawArc();
arr[i].move();
}
timer = window.requestAnimationFrame(ani);
}
ani();
document.onclick = function(){
onOff = !onOff;
if(onOff){
window.cancelAnimationFrame(timer);
}else{
ani();
}
}
function random(a,b){
return Math.ceil(Math.random() * (b-a)+a+1);
}

注意:

canvas的宽高,要在行间或这js里面书写,不要在css样式里面写,在css里设置宽高是对内容设置的,相反则是canvas的宽高;请参考网址

如果对构造函数不熟的同学可以参考这一篇博客

  • 喜欢就点个赞吧
很惭愧<br><br>只做了一点微小的工作<br><br>我会继续努力<br><br>谢谢大家