-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscriptjumpingcats.js
More file actions
58 lines (41 loc) · 1.15 KB
/
Copy pathscriptjumpingcats.js
File metadata and controls
58 lines (41 loc) · 1.15 KB
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
//<div class="cat"></div>
function getRandomInt(max)
{
return Math.floor(Math.random() * max);
}
const body = document.getElementById("body");
var catcount = 4;
for (let i = 0; i < catcount; i++) {
body.innerHTML += "<img src='/images/cat.png' class='cat'/>"
}
let posX = [];
let posY = [];
let speedX = [];
let speedY = [];
const cats = document.getElementsByClassName("cat");
console.log(cats);
for (let i = 0; i < cats.length; i++) {
posX[i] = 150 + getRandomInt(window.innerWidth - 300)
posY[i] = 150 + getRandomInt(window.innerHeight - 300)
speedX[i] = getRandomInt(10) + 1;
speedY[i] = getRandomInt(10) + 1;
}
function updatePosition()
{
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
for (let i = 0; i < cats.length; i++) {
posX[i] += speedX[i];
posY[i] += speedY[i];
if (posX[i] <= 0 || posX[i] >= windowWidth - cats[i].offsetWidth) {
speedX[i] = -speedX[i];
}
if (posY[i] <= 0 || posY[i] >= windowHeight - cats[i].offsetHeight) {
speedY[i] = -speedY[i];
}
cats[i].style.left = posX[i] + "px";
cats[i].style.top = posY[i] + "px";
}
requestAnimationFrame(updatePosition);
}
updatePosition();