Teach you to use dozens of lines of js to achieve cool canvas interactive effects

Teach you to use dozens of lines of js to achieve cool canvas interactive effects

Without further ado, here are the renderings!

The sample codes in this article are copied from a teaching video on yutube by a foreigner named Franks. He has also released many videos about canvas, which are very worth learning. I am not very familiar with canvas, so I followed the master to type the code and make a study note. I also want to say that the page structure of the example in this article is very simple (html only contains a canvas), so I will not post the following code part, after all, js is the protagonist.

1. Draw a circle

Let's start by drawing a static circle. You only need to understand a few APIs. There is a detailed description on MDN. I won't go into details here. Let's just look at the js code:

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function drawCircle() {
 ctx.beginPath();
 ctx.fillStyle = 'blue';
 ctx.arc(10, 10, 10, 0, Math.PI * 2);
 ctx.fill();
 ctx.closePath();
}
drawCircle();

Now a circle with a radius of 10px is drawn. Even people who have never used canvas can draw it in a short time. It is very simple. Next, let's add some animations on this basis.

2. Circle moved by mouse

Now if you want the circle to move with the mouse, you need to bind the mouse interaction event on the canvas. Here we focus on the mousemove/click event. As the mouse moves, the coordinates of the circle also change, so you need to update the coordinates of the circle. As for the animation, it is achieved through requestAnimationFrame. The code is a little more:

const mouse = {};
canvas.addEventListener('mousemove', (e) => {
 mouse.x = ex;
 mouse.y = ey;
});
canvas.addEventListener('click', (e) => {
 mouse.x = ex;
 mouse.y = ey;
});
canvas.addEventListener('mouseout', () => {
 mouse.x = mouse.y = undefined;
});
function drawCircle() {
 ctx.beginPath();
 ctx.fillStyle = 'blue';
 ctx.arc(mouse.x, mouse.y, 10, 0, Math.PI * 2);
 ctx.fill();
 ctx.closePath();
}
function animate() {
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 drawCircle();
 requestAnimationFrame(animate);
}
animate();

The effect is as follows. The ball can move with the mouse. It's very simple.

If you comment out ctx.clearRect in the animate function, the effect will be like this:

3. Particles dragged by the mouse

Particles are just a lot of circles with different positions, sizes, and speeds. You can initialize the particles based on the mouse event object information.

const mouse = {};
// Add new particle objects to the array when clicking or moving the mouse function addNewParticles(e) {
 mouse.x = ex;
 mouse.y = ey;
 Array.apply(null, { length: 2 }).forEach(() => {
  particlesArray.push(new Particle());
 });
}
canvas.addEventListener('mousemove', addNewParticles);
canvas.addEventListener('click', addNewParticles);
const particlesArray = [];
class Particle {
 constructor() {
  this.x = mouse.x;
  this.y = mouse.y;
  this.size = Math.random() * 5 + 1;
  this.speedX = Math.random() * 3 - 1.5; // -1.5 ~ 1.5, if it is a negative number, it moves to the left, and if it is a positive number, it moves to the right. The same is true for speedY this.speedY = Math.random() * 3 - 1.5;
 }
 update() {
  this.size -= 0.1; // The circle radius gradually decreases this.x += this.speedX; // Update the circle coordinates this.y += this.speedY;
 }
 draw() {
  ctx.beginPath();
  ctx.fillStyle = '#fff';
  ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
  ctx.fill();
  ctx.closePath();
 }
}
function handleParticles() {
 for (let i = 0; i < particlesArray.length; i++) {
  particlesArray[i].update();
  particlesArray[i].draw();
  if (particlesArray[i].size <= 0.3) { // Delete particles with too small radius particlesArray.splice(i, 1);
   i--;
  }
 }
}
function animate() {
 handleParticles();
 requestAnimationFrame(animate);
}
animate();

Now we have realized the first animation effect at the beginning of the article. Here we mainly added a Particle class to encapsulate the update and drawing of particles, and then deleted smaller particles according to conditions. It is still very simple here, with only a few dozen lines of code, but the effect is good.

4. Color gradient particles

To achieve color gradient, the video author used the HSL color model. Compared with the RGB mode we are familiar with, the color can be controlled by a variable, which is very convenient. So just make a slight change based on the third code snippet:

let hue = 0; // Hue......
class Particle {
 ......
 draw() {
  ctx.beginPath();
  ctx.fillStyle = `hsl(${hue}, 100%, 50%)`;
  ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
  ctx.fill();
  ctx.closePath();
 }
}
function handleParticles() {
 ......
}
function animate() {
    hue++;
    handleParticles();
    requestAnimationFrame(animate);
 
}
animate();

By dynamically setting the hue value and changing the fill style of the circle, you can create particles with color gradients. The effect is as shown in the second animation at the beginning.
Based on the above, you can also play new tricks, such as changing it like this:

function animate() {
 // ctx.clearRect(0, 0, canvas.width, canvas.height);
 ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
 ctx.fillRect(0, 0, canvas.width, canvas.height);
 hue++;
 handleParticles();
 requestAnimationFrame(animate);
}

Now our particles have a trailing effect, which is the third animation at the beginning of the article. Here, the transparency of the entire canvas is superimposed to make the previous painting effect fade and finally hide it. From a visual point of view, it is a gradient trailing effect. So far, the effect is getting more and more interesting, but there is still very little code.

5. Connected Particles

Finally, we need to connect the particles, which is the fourth animation effect at the beginning of the article. Based on the previous animation, we can draw a straight line between the two circles. Of course, we need to get the distance between the centers of the two circles and then draw them. This involves the modification of the handleParticles function, and the rest remains unchanged.

function handleParticles() {
 for (let i = 0; i < particlesArray.length; i++) {
  particlesArray[i].update();
  particlesArray[i].draw();
  // Starting from the current particle, traverse the following particles and calculate the corresponding distances one by one for (let j = i + 1; j < particlesArray.length; j++) {
   const dx = particlesArray[i].x - particlesArray[j].x;
   const dy = particlesArray[i].y - particlesArray[j].y;
   const distance = Math.sqrt(dx * dx + dy * dy); // Junior high school knowledgeif (distance < 100) { // The distance is too large to be discarded, otherwise the visual effect will be poor// Draw a straight linectx.beginPath();
    ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
    ctx.moveTo(particlesArray[i].x, particlesArray[i].y);
    ctx.lineTo(particlesArray[j].x, particlesArray[j].y);
    ctx.stroke();
    ctx.closePath();
   }
  }
  if (particlesArray[i].size <= 0.3) {
   particlesArray.splice(i, 1);
   i--;
  }
 }
}

By adding a loop and drawing straight lines, the effect is achieved, and it looks very good. Up to here, I have basically followed the author's steps. The amount of code is not large, but the effect is very good. More importantly, my enthusiasm for learning canvas has been rekindled.

Summarize

This concludes the article that teaches you how to use dozens of lines of js to achieve cool canvas interactive effects. For more relevant content on how to use js to achieve canvas interactive effects, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript+html5 canvas to achieve image fragmentation and reorganization animation effects
  • js canvas realizes starry sky background effect
  • JavaScript canvas to achieve meteor effects
  • js canvas realizes random particle effects

<<:  How to create a Pod in Kubernetes

>>:  The most basic code for web pages

Recommend

HTML solves the problem of invalid table width setting

If you set the table-layer:fixed style for a tabl...

Use JS to operate files (FileReader reads --node's fs)

Table of contents JS reads file FileReader docume...

CSS--overflow:hidden in project examples

Here are some examples of how I use this property ...

How to build your own Nexus private server in Linux

This article describes how to build a Nexus priva...

Docker - Summary of 3 ways to modify container mount directories

Method 1: Modify the configuration file (need to ...

How to make Python scripts run directly under Ubuntu

Let’s take the translation program as an example....

Detailed process of zabbix monitoring process and port through agent

Environment Introduction Operating system: centos...

Vue achieves seamless carousel effect

This article shares the specific code of Vue to a...

docker cp copy files and enter the container

Enter the running container # Enter the container...

...

Docker exposes port 2375, causing server attacks and solutions

I believe that students who have learned about th...

Detailed explanation of how to use the mysql backup script mysqldump

This article shares the MySQL backup script for y...

Talking about the practical application of html mailto (email)

As we all know, mailto is a very practical HTML ta...

Detailed explanation of JavaScript Proxy object

Table of contents 1. What is Proxy? 2. How to use...