原文链接:http://www.jianshu.com/p/c921d70812a5
著作权归原作者所有:ToyLevom 简书
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
|
<!DOCTYPE html>
<
html
>
<
head
>
<
meta
charset= "utf-8">
<
title
></
title
>
<!--<script src="jquery-1.9.1.min.js"></script>-->
<
style
>
* {
margin: 0;
padding: 0;
}
html,body {
width: 100%;
height: 100%;
/*解决canvas的内联块的上下出现边隙(浮动也可以解决)*/
/*font-size: 0;*/
}
canvas {
/*解决canvas的内联块的上下出现边隙(浮动也可以解决)*/
display: block;
}
</
style
>
</
head
>
<
body
>
<
canvas
width
=
"500"
height
=
"500"
id
=
"cavas"
></
canvas
>
<
script
src
=
"scripts/test.js"
></
script
>
</
body
>
</
html
>
|
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
|
var
cavas = document.getElementById(
"cavas"
);
var
body = document.getElementsByTagName(
"body"
)[0];
var
cxt = cavas.getContext(
"2d"
);
cavas.width = body.offsetWidth;
cavas.height = body.offsetHeight;
var
cwidth = cavas.width;
var
cheight = cavas.height;
//创建随机函数
function
random(max,min,notNum){
var
result = parseInt(Math.random()*(max - min)+ min);
if
(result == notNum){
//指定不想要出现的随机数
result++;
}
return
result;
}
//随机颜色函数
function
randomColor() {
return
"rgba("
+ random(0, 255) +
","
+ random(0, 255) +
","
+ random(0, 255) +
","
+ (Math.random() + 0.1).toFixed(2) +
")"
;
}
//创建构造函数
function
Ball(x,y,r,speedX,speedY,color){
this
.r = r||random(10,30)
this
.x = x||random(
this
.r, cwidth -
this
.r);
this
.y = y||random(
this
.r, cheight -
this
.r);
this
.color = color || randomColor();
this
.speedX = speedX || random(-5, 5, 0);
this
.speedY = speedY || random(-5, 5, 0);
//创建小球画布
this
.draw =
function
(){
cxt.fillStyle =
this
.color;
cxt.beginPath();
cxt.arc(
this
.x,
this
.y,
this
.r,0,Math.PI*2,
true
);
cxt.closePath();
cxt.fill();
}
//创建小球移动
this
.move =
function
(){
this
.x +=
this
.speedX;
//速度是固定的
this
.y +=
this
.speedY;
//如果小球在最边上,则反弹回来
if
(
this
.x > cwidth -
this
.r ||
this
.x <
this
.r){
this
.speedX = -
this
.speedX;
}
if
(
this
.y > cheight -
this
.r ||
this
.y <
this
.r){
this
.speedY = -
this
.speedY;
}
this
.draw();
}
}
//创建100个小球对象
var
arrBall = [];
for
(
var
i=0; i < 100; i++){
var
ball =
new
Ball();
arrBall.push(ball)
//将生成的对象放进数组
}
//小球移动
setInterval(
function
(){
cxt.clearRect(0, 0, cwidth , cheight);
for
(
var
i = 0,len = arrBall.length; i < len; i++){
arrBall[i].move();
}
},16)
|
本文转自 小旭依然 51CTO博客,原文链接:http://blog.51cto.com/xuyran/1886859