| 2022-03-27
How to Create a Gravity Effect in the HTML5 Canvas
Create a gravity effect with javascript and HTML5 canvas.
Start by setting up some constants.
var gravity = .75;
var friction = 0.85;
const circleArray = [];
let ballArray = [];
var ball;
JavaScript
Add a Ball class
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 > canvas.height) {
this.dy = -this.dy * friction;
} else {
this.dy += gravity;
}
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 () {
ctx.beginPath();
ctx.arc(this.x, this.y - this.dy, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.strokeStyle = 'orange'
ctx.fill();
ctx.stroke();
ctx.closePath();
}
}
JavaScript
The init function builds an array of balls.
function init() {
ball = new Ball(canvas.width / 2, canvas.height / 2, 2, 30, 'red')
console.log(ball)
for (let i = 0; i < 300; i++) {
let radius = Math.random() * 6 + 1;
let x = Math.random() * (canvas.width - radius) + radius;
let y = Math.random() * (canvas.height - radius * 4 - 100) + radius;
let dx = (Math.random() - 0.5) * 2;
let dy = (Math.random() - 0.5) * 2;
ballArray.push(new Ball(x, y, dx, dy, radius, 'red'))
}
console.log(ballArray)
}
JavaScript
The animate function runs the update method on each ball instance.
function animate() {
requestAnimationFrame(animate)
console.log('animate')
ctx.clearRect(0, 0, innerWidth, innerHeight)
ctx.fillStyle = 'white'
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < ballArray.length; i++) {
ballArray[i].update()
}
//ctx.clearRect(0, 0, innerWidth, innerHeight)
}
JavaScript
Download the app here. View page source to see the code.
This project was inspired from the Chris Course tutorial linked here.
Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.