JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="500" height="500" style="border: 1px solid rgb(0, 0, 0);"></canvas>
CSS
#canvas {
background: transparent;
background-color: rgba(0, 0, 0, 0.1)
}
JavaScript
var bubbles = new Array();
var canvas = null;
var context = null;
var w = 500;
var h = 500;
//Starts the animation when the page is loaded.
window.onload = function(){
//Retrieves the canvas and creates a context.
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
//Creates 20 new bubbles.
for(var i = 0; i < 20; i++){
var bubble = new Object;
//The size is randomized: 10, 20 or 30px.
bubble.size = Math.ceil(Math.random()*3) * 10;
//The starting position is randomized.
bubble.x = Math.floor(Math.random()*(w-2*bubble.size))+bubble.size;
bubble.y = Math.floor(Math.random()*(h-2*bubble.size))+bubble.size;
//The direction and speed is randomized.
bubble.dirX = Math.random()*3;
bubble.dirY = Math.random()*3;
//Creates an array for each color and an array for each color changing speed.
bubble.colorValue = new Array();
bubble.colorDir = new Array();
bubble.colorValue[1] = Math.floor(Math.random()*150)+50;
bubble.colorValue[2] = Math.floor(Math.random()*150)+50;
bubble.colorValue[3] = Math.floor(Math.random()*150)+50;
bubble.colorDir[1] = Math.ceil(Math.random()*2);
bubble.colorDir[2] = Math.ceil(Math.random()*2);
bubble.colorDir[3] = Math.ceil(Math.random()*2);
//A function that generated the output for the color.
bubble.toColor = function(){
return this.colorValue[1]+","+this.colorValue[2]+","+this.colorValue[3];
}
//A function that changes each color according to their speed. When it reaches max, it reverts the direction.
bubble.changeColor = function(){
for(var c = 1; c <= 3; c++){
this.colorValue[c] += this.colorDir[c];
if(this.colorValue[c] >= 200 || this.colorValue[c] <= 50){
this.colorDir[c] = -(this.colorDir[c]);
}
}
}
//This function moves the bubbles, and it works the same way as the color changing function.
bubble.move = function(){
this.x += this.dirX;
this.y += this.dirY;
if(this.x <= this.size || this.x >= w-this.size){this.dirX =...