Skip to content

Instantly share code, notes, and snippets.

@JonathanDn
Created October 16, 2019 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanDn/ef91a979acc4f0a31e56047dedfab17d to your computer and use it in GitHub Desktop.
Save JonathanDn/ef91a979acc4f0a31e56047dedfab17d to your computer and use it in GitHub Desktop.
HTML Canvas Gravity
body {
margin: 0;
overflow: hidden;
}
<canvas></canvas>
// Initial Setup
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
// Variables
var mouse = {
y: innerWidth / 2,
x: innerHeight / 2
}
var colors = [
'#3F5B73',
'#8EB1BF',
'#F2EB8D',
'#D99A4E',
'#BF8049'
];
var gravity = 1;
var friction = 0.5;
// Event Listeners
addEventListener("mousemove", function(){
mouse.x = event.clientX,
mouse.y = event.clientY
});
addEventListener("click", function() {
init();
});
addEventListener("resize", function() {
canvas.width = innerWidth,
canvas.height = innerHeight
init();
});
// Utility Functions
function randomIntFromRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function randomColor(colors) {
return colors[Math.floor(Math.random() * colors.length)];
}
function Ball(x, y, dx, dy, radius, color) {
this.x = x;
this.y = y;
this.dy = dy;
this.dx = dx;
this.radius = radius;
this.color = color;
this.update = function() {
if (this.y + this.radius + this.dy > canvas.height) {
this.dy = -this.dy * friction; // decrease every time ball hits floor
} else {
this.dy += gravity; // add another value ontop of the current velocity
}
if (this.x + this.radius + this.dx > canvas.width ||
this.x - this.radius < 0) {
this.dx = -this.dx;
}
this.x += this.dx;
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.stroke();
c.closePath();
}
}
// Implementation
var ball;
var ballArray = [];
function init() {
ballArray = [];
for (var i = 0; i < 500; i++) {
var radius = randomIntFromRange(8, 20);
var x = randomIntFromRange(radius, canvas.width - radius);
var y = randomIntFromRange(radius, canvas.height - radius);
var dx = randomIntFromRange(-2, 2);
var dy = randomIntFromRange(-2, 2);
var color = randomColor(colors);
ballArray.push(new Ball(x, y, dx, dy, radius, color));
}
}
// Animation Loop
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < ballArray.length; i++) {
ballArray[i].update();
}
}
init();
animate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment