This is the 30th day of my participation in the August Challenge
Implementation effect
Super cool
Realize the principle of
- Create a small ball
- Add a random color, random radius to the ball
- Mouse movement through instantiation, new ball
- Animate the ball by calling the method added to the prototype
- Constantly update the canvas with a timer
The implementation process
Create a small ball
By creating a function to receive all the style of the Ball, and then through the instantiation function, the current position of the mouse is passed to the Ball function, so that the Ball created by instantiation, and finally the Ball created into an array, the array in the form of objects to store the attributes and attribute values of each Ball
function Ball(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.color = getRandom();// Randomly generate colors
this.dx = parseInt(Math.random() * 10) - 5;// Generate random moving positions
this.dy = parseInt(Math.random() * 10) - 5;// '-5' allows the ball to move around randomly
ballArr.push(this);// Add a ball
}
// Listen for mouse movement events
canvas.addEventListener('mousemove'.function (e) {
new Ball(e.offsetX, e.offsetY, parseInt(Math.random() * 20));
/* Instantiate Ball as a prototype-calling method for the Ball object */
})
Copy the code
Generate random colors
For the color attribute, a color can be represented by a six-digit hexadecimal value
Therefore, a random color can be generated by randomly generating a hexadecimal number of 6 digits
By storing the 16 numbers from 0 to f in an array, we can randomly fetch 6 numbers from 0 to f by randomly generating 6 index values from 0 to 16
Split splits a string with the arguments in parentheses as identifiers, returning an array
// Set a random color
function getRandom() {
var allType = '0,1,2,3,4,5,6,7,8,9, a, b, c, d, e, f';// Hexadecimal color
var allTypeArr = allType.split(', ');// Split into arrays with ','
var color = The '#';
for (var i = 0; i < 6; i++) {
// Generate a random number from 0 to 16
var random = parseInt(Math.random() * allTypeArr.length);
color += allTypeArr[random];
}
return color;// Returns a randomly generated color
}
Copy the code
Render a ball
Add render methods to the prototype chain of functions, with each object instantiated by the Ball function carrying these methods
This function generates a circle from the Ball argument. When instantiated, it generates an object containing the values x,y, and r
Ball.prototype.render = function () {
ctx.beginPath();// The path starts
ctx.arc(this.x, this.y, this.r, 0.Math.PI * 2.false);// Draw the circle, position, radius
ctx.fillStyle = this.color;/ / color
ctx.fill();/ / fill
}
Copy the code
Update ball information
Because the resulting balls x,y, and R are fixed, the positions of the balls are also fixed and will not change
Therefore, you need to change the position and radius of each ball to make the ball move. When the radius of the ball is less than 0, the remove method is called to remove the ball from the array
/* Updates ball position and clears when radius is less than 0
Ball.prototype.update = function () {
this.x += this.dx;/ / x change
this.y += this.dy;/ / y change
this.r -= 0.1;// The radius decreases
if (this.r < 0) {
this.remove();// Call the added remove method}}Copy the code
Delete the ball
So this is the remove method that’s called up here, and when this, which is the radius of the current sphere, is less than zero, I go through the array, find this, which is the sphere, and remove that element of the array by calling the method in the array
The splice(index,num) method deletes num elements starting from index
Ball.prototype.remove = function () {
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);// Find the element that is less than 0 and delete it}}}Copy the code
Apply colours to a drawing canvas
Through the timer, constantly update the canvas, mainly these steps
- Remove the canvas
- Go through the number group, get all the ball information, render to the canvas
- Call over and over again to update the ball information
setInterval(function () {
ctx.clearRect(0.0, canvas.width, canvas.height);/ / clear screen
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].update();// Update the ball
if (ballArr[i]) {
ballArr[i].render();// Render the ball}}},20);
Copy the code
The complete code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
body {
background: black;
}
canvas {
display: block;
border: 1px solid black;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas width="1000px" height="1000px" id="myCanvas">The current browser version is not supported. Upgrade the browser</canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Define the position and radius of the ball
function Ball(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.color = getRandom();// Randomly generate colors
this.dx = parseInt(Math.random() * 10) - 5;// Generate random moving positions
this.dy = parseInt(Math.random() * 10) - 5;
ballArr.push(this);// Add a ball
}
/* Updates ball position and clears when radius is less than 0
Ball.prototype.update = function () {
this.x += this.dx;
this.y += this.dy;
this.r -= 0.1;
if (this.r < 0) {
this.remove();// Call the added remove method
}
}
Ball.prototype.remove = function () {
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);// Find the element that is less than 0 and delete it}}}// Render the ball to draw the ball
// Add methods to the prototype
Ball.prototype.render = function () {
ctx.beginPath();// The path starts
ctx.arc(this.x, this.y, this.r, 0.Math.PI * 2.false);// Draw the circle, position, radius
ctx.fillStyle = this.color;/ / color
ctx.fill();
}
// Listen for mouse movement events
canvas.addEventListener('mousemove'.function (e) {
new Ball(e.offsetX, e.offsetY, parseInt(Math.random() * 20));
// Instantiate Ball as a prototype-calling method for the Ball object through __proto__
console.log(ballArr);
})
var ballArr = [];
setInterval(function () {
ctx.clearRect(0.0, canvas.width, canvas.height);/ / clear screen
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].update();// Update the ball
if (ballArr[i]) {
ballArr[i].render();// Render the ball}}},20);
// Set a random color
function getRandom() {
var allType = '0,1,2,3,4,5,6,7,8,9, a, b, c, d, e, f';// Hexadecimal color
var allTypeArr = allType.split(', ');// Split into arrays with ','
var color = The '#';
for (var i = 0; i < 6; i++) {
var random = parseInt(Math.random() * allTypeArr.length);
// Generate a random number from 0 to 16
color += allTypeArr[random];
}
return color;// Returns a randomly generated color
}
</script>
</body>
</html>
Copy the code