<!-- Draw bubble effect -->
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<style type="text/css">
#canvas{
border: 1px solid #eee;
}
</style>
<body>
<canvas id="canvas" width="500" height="300" ></canvas>
<!-- It is not recommended to use CSS to control the width, because if the set width and height are different from the initial ratio of 300:150, distortion may occur -->
<!-- If the browser does not support canvas, you can directly use <canvas>Your browser does not support canvas</canvas> and the browser will render alternative content -->
</body>
<script type="text/javascript">
class Bubble{ // ES6 added Class syntax
constructor(ctx){ // Constructor
this.colorList = [[254,158,159], [147,186,255], [217,153,249], [129,199,132], [255,202,98], [255,164,119]]; // Color scheme
this.ctx = ctx.getContext("2d"); // 2D drawing
this.circleList = []; // Bubble array
}
randomInt(a, b) { // Return a random number
return Number.parseInt(Math.random() * (b - a + 1) + a); // Get a random value between a and b, including a and b
}
newCircle(){ // New bubble
if(this.randomInt(0,50)) return 0; // Control the number of bubbles generated
var canvasHeight = this.ctx.canvas.height; // Get the canvas height
var circle = {}; // Define a new bubble object
circle.r = this.randomInt(10,50); // Random radius
circle.x = this.randomInt(0, this.ctx.canvas.width); // Initialize the X coordinate of the bubble
circle.xMoveSpeed = this.randomInt(-10,10); // X direction movement speed and direction
circle.y = canvasHeight + circle.r; // Initialize the Y coordinate of the bubble
circle.yMoveSpeed = this.randomInt(5,10); // Y direction movement speed
circle.color = this.colorList[this.randomInt(0,this.colorList.length-1)]; // Get the bubble color
this.circleList.push(circle); // Put the object into the array
}