-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclass.html
71 lines (62 loc) · 2.44 KB
/
class.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
<html>
<head>
<style>
#container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: lightblue;
}
.ball {
width: 50px;
height: 50px;
border-radius: calc(50px/2);
background-color: lightgreen;
border: 1px dashed grey;
position: absolute;
transition: left 0.075s, top 0.075s, background-color 2s;
/* Use CSS animations to reduce motion jerk while fading in the background color changes */
}
</style>
</head>
<body>
<div id='container'></div>
<script>
var Ball = function(radius, x, y) {
var instance = this; // grab a pointer to 'this'
this.radius = radius; // save our radius
this.html = document.createElement('div'); // create the HTML we'll use
this.html.classList.add('ball'); // add a class to connect to our CSS
var styling = { // Define a dictionary for the various CSS attributes we want to style
width: 2*this.radius + 'px',
height: 2*this.radius + 'px',
borderRadius: this.radius + 'px',
left: x + '%',
top: y + '%',
backgroundColor: 'rgba(' + [parseInt(Math.random() * 255), parseInt(Math.random() * 255), parseInt(Math.random() * 255), Math.random()].join(',') + ')'
};
Object.keys(styling).forEach(function(key) { // iterate over them and set them
instance.html.style[key] = styling[key];
});
document.getElementById('container').appendChild(instance.html); // add ourselves to the HTML
this.animateLoop = setInterval(function() { // Create our animate loop and save a pointer to it in this.animateLoop
// and then start up a timer which randomly modifies the position
instance.html.style.left = parseFloat(instance.html.style.left) + (-1 + Math.random() * 2) + '%'
instance.html.style.top = parseFloat(instance.html.style.top) + (-1 + Math.random() * 2) + '%'
}, 75);
this.html.addEventListener('click', function(event) {
// Add some functionality so that when we click on it we turn off our loop
clearInterval(instance.animateLoop);
});
}
window.addEventListener('load', function(event) { // When the page loads
// Make 10 balls;
for (var i = 0; i < 10; i++) {
new Ball(Math.random()*100, Math.random()*90 + '%', Math.random()*90 + '%');
}
});
</script>
</body>
</html>