forked from enrod92/jsCircles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
executable file
·105 lines (85 loc) · 2.49 KB
/
index.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<html>
<head>
<title>Javascript Box - OOP demo</title>
</head>
<body>
<svg id="svg" xmlns="http://www.w3.org/2000/svg"></svg>
<script>
function Circle(cx, cy, html_id)
{
var html_id = html_id;
this.info = { cx: cx, cy: cy };
//private function that generates a random number
var randomNumberBetween = function(min, max){
return Math.random()*(max-min) + min;
}
this.initialize = function(){
//give a random velocity for the circle
this.info.velocity = {
x: randomNumberBetween(-3,3),
y: randomNumberBetween(-3,3)
}
//create a circle
var circle = makeSVG('circle',
{ cx: this.info.cx,
cy: this.info.cy,
r: 10,
id: html_id,
style: "fill: black"
});
document.getElementById('svg').appendChild(circle);
}
this.update = function(time){
var el = document.getElementById(html_id);
//see if the circle is going outside the browser. if it is, reverse the velocity
if( this.info.cx > document.body.clientWidth || this.info.cx < 0)
{
this.info.velocity.x = this.info.velocity.x * -1;
}
if( this.info.cy > document.body.clientHeight || this.info.cy < 0)
{
this.info.velocity.y = this.info.velocity.y * -1;
}
this.info.cx = this.info.cx + this.info.velocity.x*time;
this.info.cy = this.info.cy + this.info.velocity.y*time;
el.setAttribute("cx", this.info.cx);
el.setAttribute("cy", this.info.cy);
}
//creates the SVG element and returns it
var makeSVG = function(tag, attrs) {
var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
{
el.setAttribute(k, attrs[k]);
}
return el;
}
this.initialize();
}
function PlayGround()
{
var counter = 0; //counts the number of circles created
var circles = [ ]; //array that will hold all the circles created in the app
//a loop that updates the circle's position on the screen
this.loop = function(){
for(circle in circles)
{
circles[circle].update(1);
}
}
this.createNewCircle = function(x,y){
var new_circle = new Circle(x,y,counter++);
circles.push(new_circle);
// console.log('created a new circle!', new_circle);
}
//create one circle when the game starts
this.createNewCircle(document.body.clientWidth/2, document.body.clientHeight/2);
}
var playground = new PlayGround();
setInterval(playground.loop, 15);
document.onclick = function(e) {
playground.createNewCircle(e.x,e.y);
}
</script>
</body>
</html>