Small tutorial: HTML5 canvas Canvas drawing generates various particle physics dynamic effects

 

content:

1. Draw static particle graphics effects

2. Add static particle animation effects

3. Add particle collision animation effect

4. Add particle collision effect

 

Basic requirements:

1. Understand basic HTML tags, such as the canvas tag

2. Understand the basics of Javascript

 


 

Step 1: Generate Static Particle Graphics

To generate static particle graphics, we will use the following related methods of Canvas:

 

  • context.fillRect(x, y, width, height);
  • context.arc(x, y, r, sAngle, eAngle, counterclockwise);

 

Among them, the fillRect method is used to generate the entire animation scene, covering the entire area of ​​the canvas, and then the arc method is used to generate a circle. The arc method itself is used to generate an arc, but if a 360-degree arc is generated, it is natural The circle is generated, and the complete code is as follows:

 

var canvas = document.getElementById('gbcanvas'),
    context = canvas.getContext('2d');

var posX = 30, //Define the X coordinate of the center of the circle
    posY = 30, //Define the Y coordinate of the center of the circle
    particleRadius = 30; //Define the radius

context.fillStyle = '#E4E4E4';
context.fillRect(0,0,canvas.width,canvas.height); //Generate canvas background color

context.beginPath();
context.fillStyle = '#dd4814';
context.arc(posX, posY, particleRadius, 0 , Math.PI*2, true);
context.closePath();
context.fill();

 

Online demo & debugging address

 


 

Step 2: Generate the particle running effect

Animation effect principle:

The principle of HTML5 canvas animation generation, in essence, the implementation method is to redraw the graphics in the canvas every fixed period of time. The following is the code:

var canvas = document.getElementById('gbcanvas'),
    context = canvas.getContext('2d'),
    posX = 30,
    posY = 30,
    particleRadius = 30;
      
      
    //Define setInterval to generate particles at a specific time, as follows
    setInterval(function(){
      //In order to be able to generate particle movement effects, we need to clear the drawing in the interface before drawing particles each time
      context.fillStyle = '#E4E4E4';
      context.fillRect(0,0,canvas.width,canvas.height); //fill with background color
      
      posX+=2;
      posY+=1;
      
      context.beginPath();
      context.fillStyle = '#dd4814';
      context.arc(posX, posY, particleRadius, 0, Math.PI*2, true);
      
      context.closePath();
      context.fill();
    }, 10);

In the above code, we use the fillRect method to first refill the entire background color, and then use the arc method to redraw the circle to generate a moving effect

 

Online demo & debugging address

Click here for the specific tutorial: http://igeekbar.com/igeekbar/post/172.htm

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326613453&siteId=291194637