<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Canvas Bubble Animation</title>
</head>
<body>
<canvas>
</canvas>
</body>
</html>
body {
margin: 0;
padding: 0;
}
canvas {
width: 100%;
height: 100%;
}
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var canvasContext = canvas.getContext('2d');
function Circle (x, y, dx, dy, radius, color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color;
this.draw = function () {
canvasContext.beginPath();
canvasContext.arc(this.x, this.y, this.radius, 0, 2*Math.PI, false);
canvasContext.lineWidth = 2;
canvasContext.strokeStyle = this.color;
canvasContext.stroke();
}
this.update = function () {
if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {
this.dy = -this.dy;
}
this.x+=this.dx;
this.y+=this.dy;
this.draw();
}
}
var colorPalette = ["#e55039", "#78e08f", "#f6b93b", "#60a3bc", "#A3CB38", "#B53471", "#EE5A24", "#12CBC4"];
var circleArray = [];
for (var i = 0; i < 20; i++) {
var x = Math.random()*(innerWidth-200)+100;
var y = Math.random()*(innerHeight-200)+100;
var radius =60;
var dx = (Math.random() - 0.5) * 8;
var dy = (Math.random() - 0.5) * 8;
var color = colorPalette[Math.round(Math.random()*(colorPalette.length-1))];
circleArray.push(new Circle(x, y, dx, dy, radius, color));
}
function animate() {
requestAnimationFrame(animate);
canvasContext.clearRect(0, 0, innerWidth, innerHeight);
for (var i = 0; i < circleArray.length; i++) {
circleArray[i].update();
}
}
animate();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.