Testing requestAnimationFrame
This commit is contained in:
commit
56c478d614
8
index.html
Normal file
8
index.html
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<script src="index.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<canvas id="canvas"></canvas>
|
||||||
|
</body>
|
||||||
|
</html>
|
69
index.js
Normal file
69
index.js
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', init);
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
var canvas = document.getElementById("canvas");
|
||||||
|
canvas.width = window.innerWidth
|
||||||
|
canvas.height = window.innerHeight
|
||||||
|
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
var balls = [];
|
||||||
|
add();
|
||||||
|
document.addEventListener('keydown', control);
|
||||||
|
|
||||||
|
anim();
|
||||||
|
|
||||||
|
function control(e) {
|
||||||
|
switch(e.key) {
|
||||||
|
case 'ArrowUp': add(); break;
|
||||||
|
case 'ArrowDown': remove(); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove() {
|
||||||
|
balls.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
function add() {
|
||||||
|
let x = Math.floor(Math.random() * canvas.width);
|
||||||
|
let y = Math.floor(Math.random() * canvas.height);
|
||||||
|
let speed = 1 + Math.floor(Math.random() * 10);
|
||||||
|
let angle = Math.floor(Math.random() * 360);
|
||||||
|
|
||||||
|
// angle must be in radians (now it's wrong)
|
||||||
|
balls.push({ x: x, y: y, size: 20, speed: speed, angle: angle, color:'black' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function anim() {
|
||||||
|
ctx.fillStyle = 'white';
|
||||||
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
balls.forEach(b => {
|
||||||
|
update(b);
|
||||||
|
draw(b);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
requestAnimationFrame(anim);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function update(b) {
|
||||||
|
b.x += b.speed * Math.cos(b.angle);
|
||||||
|
b.y += b.speed * Math.sin(b.angle);
|
||||||
|
|
||||||
|
if ( b.x<0 || b.x>canvas.width || b.y<0 || b.y>canvas.height ) bounce(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bounce(b) {
|
||||||
|
b.angle += 180;
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw(b) {
|
||||||
|
ctx.fillStyle = b.color;
|
||||||
|
ctx.fillRect(b.x, b.y, b.size, b.size);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user