HTML5 Javascript Canvas Gravity

by Spsoi

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>

CSS

canvas {
    border: 1px solid #000;
}

JavaScript

canvas = document.querySelector('#canvas');
let c = canvas.getContext('2d');

let mouse = {
    x: innerWidth / 2,
    y: innerHeight / 2
}

document.addEventListener("mousemove", function(event){
    mouse.x = event.clientX;
    mouse.y = event.clientY;
});

let gravity = 1;
let friction = 0.9;

function Ball (x, y, dy, radius, color) { // шарик
    // 2
    this.x =x;
    this.y = y;
    this.dy = dy; // скорость падения вниз
    this.radius = radius;
    this.color = color;

    this.update = function() {
        if (this.y + this.radius > canvas.height) { // отскок
            this.dy = -this.dy * friction; // гравитация
        }else {
            this.dy += gravity; // отскок
        }
        this.y += this.dy;
        this.draw();
    }

    this.draw = function () {
        c.beginPath();
            c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
            c.fillStyle = this.color;
            c.fill();
        c.closePath();
    }
}

let ball;
function init() { // точка входа
    // 1
    ball = new Ball (canvas.width / 2, canvas.height / 2, 10, 30, 'red');
}

function animate() {
/*     console.log(mouse.x);
    console.log(mouse.y); */
    c.clearRect(0,0, canvas.width, canvas.height);
    ball.update(); 
    requestAnimationFrame(animate);
}

init();
animate();