HTML5 Game - Canvas Animation Particle

Simulating particle physics

The following code simulate particle physics by modeling gravity, boundary conditions, collision damping, and floor friction.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <script>
class MyObject{/*from  w w  w .j  av a 2  s.c  om*/
   draw(animationController){
      let canvas = animationController.getCanvas();
      let context = animationController.getContext();

                // physics globals
                let gravity = 1500; // pixels / second^2
                let collisionDamper = 0.8; // 80% velocity lost when collision occurs
                let floorFriction = 100; // pixels / second^2
                let timeInterval = animationController.getTimeInterval();
                
                // gravity
                this.vy += gravity * timeInterval / 1000;
                
                // position
                this.y += this.vy * timeInterval / 1000;
                this.x += this.vx * timeInterval / 1000;
                
                // floor condition
                if (this.y > (canvas.height - this.radius)) {
                    this.y = canvas.height - this.radius;
                    this.vy *= -1;
                    this.vy *= collisionDamper;
                }
                
                // floor friction
                if (this.y == canvas.height - this.radius) {
                    if (this.vx > 0.1) {
                        this.vx -= floorFriction * timeInterval / 1000;
                    }
                    else if (this.vx < -0.1) {
                        this.vx += floorFriction * timeInterval / 1000;
                    }
                    else {
                        this.vx = 0;
                    }
                }
                
                // celing  condition
                if (this.y < (this.radius)) {
                    this.y = this.radius;
                    this.vy *= -1;
                    this.vy *= collisionDamper;
                }
                
                // right wall condition
                if (this.x > (canvas.width - this.radius)) {
                    this.x = canvas.width - this.radius;
                    this.vx *= -1;
                    this.vx *= collisionDamper;
                }
                
                // left wall condition
                if (this.x < (this.radius)) {
                    this.x = this.radius;
                    this.vx *= -1;
                    this.vx *= collisionDamper;
                }    
      
      context.beginPath();
      context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
      context.fillStyle = "red";
      context.fill();      
   }
   constructor(){
      this.x = Math.random()*100;
      this.y = Math.random()*100;
      this.width = 10;
      this.height = 10;
      this.radius = 10;
         this.vx = 600;
         this.vy = -900;

   }
   
}    
class MyAnimation {
   constructor(canvasId){
        this.canvas = document.getElementById(canvasId);
        this.context = this.canvas.getContext("2d");
        this.t = 0;
        this.timeInterval = 0;
        this.startTime = 0;
        this.lastTime = 0;
        this.frame = 0;
        this.animating = false;
        

        window.requestAnimFrame = (function(callback){
            return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback){
                window.setTimeout(callback, 1000 / 60);
            };
        })();
   }
   getContext(){
      return this.context;
   };

   getCanvas(){
      return this.canvas;
   };

   clear(){
       this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
   };

   setDrawStage(func){
       this.drawStage = func;
   };

   isAnimating = function(){
       return this.animating;
   };

   getFrame(){
      return this.frame;
   };

   start(){
        this.animating = true; 
        let date = new Date();
        this.startTime = date.getTime();
        this.lastTime = this.startTime;
        
        if (this.drawStage !== undefined) {
            this.drawStage();
        }
        
        this.animationLoop();
   };

   stop(){
       this.animating = false;
   };

   getTimeInterval(){
       return this.timeInterval;
   };

   getTime(){
    return this.t;
   };

   getFps(){
      return this.timeInterval > 0 ? 1000 / this.timeInterval : 0;
   };

   animationLoop(){
        let that = this;
        
        this.frame++;
        let date = new Date();
        let thisTime = date.getTime();
        this.timeInterval = thisTime - this.lastTime;
        this.t += this.timeInterval;
        this.lastTime = thisTime;
        
        if (this.drawStage !== undefined) {
            this.drawStage();
        }
        
        if (this.animating) {
            requestAnimFrame(function(){
                that.animationLoop();
            });
        }
    }   
} 
            window.onload = function(){
                let myAnimation = new MyAnimation("myCanvas");
                let canvas = myAnimation.getCanvas();
                let context = myAnimation.getContext();
                let myObject = new MyObject();
                let myObject2 = new MyObject();
                myAnimation.setDrawStage(function(){
                     myAnimation.clear();
                     myObject.draw(myAnimation);
                     myObject2.draw(myAnimation);
                     
                });
                myAnimation.start();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

To simulate particle physics, control the particle's x and y position and its velocity in both the x and y direction for each frame.

The movement of the particle is based on the sum of all the forces acting on the particle.

The gravity is pulling the particle downwards.

The collisions against the walls, ceiling, and floor will reduce the particle's velocity according.

The floor friction will reduce the particle's horizontal speed when it rolls on the floor.

Related Topic