JSFiddle - React, Tailwind, and code Playground
HTML
<canvas width="600" height="400" id="canvas">
<p>Your browser does not support canvas =[ </p>
</canvas>
CSS
#canvas {
border: 1px solid #000000;
margin: 0 auto;
}
JavaScript
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("canvas"); //create variable canvas
context = canvas.getContext("2d"); //create variable cx
function bubble(x, y, r) {
var randx = Math.floor(Math.random() * canvas.width - 50); //random on the x axis
var randy = Math.floor(Math.random() * canvas.height + 200); //random on the y axis
this.x = randx || x || 0; //this.x = a random x on the canvas
this.y = randy || y || 0; //this.y = the top y position of the canvas
this.r = r || 0; //this.r = specified by me
this.expired = false; //set expired for the bubble to false
this.draw = function() { //create the draw function
context.beginPath();
context.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false); //fill the circle
context.fillStyle = "green"; //set the inside of the bubble to blue
context.fill();
context.lineWidth = 1;
context.strokeStyle = "black";
context.stroke();
};
this.update = function() { //create the function for update
this.y--; //everytime this function runs, move the bubble up the y axis by one
if (y < canvas.height) { //if the y axis of the bubble is less than the height of the canvas
this.expired = true; //make the bubble disappear
}
};
}
var bubbles = new Array(); //create a new array for the bubbles
function newBubble() { //create function for a new bubble
bubbles.push(new bubble(window.randx, window.randy, 30));
}
var time = 0;
function loop() {
context.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
if (time % 10 === 0) { //if the time is directly divisable into 0 make a new bubble
newBubble(); //create a new bubble
}
for (var i = 0, l = bubbles.length; i < l; i++)...