Javascript particle animation around a ring - Javascript Canvas

Javascript examples for Canvas:Animation

Description

Javascript particle animation around a ring

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){//from ww  w  . j a v  a2 s  . c  o m
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var W = canvas.width; var H = canvas.height;
var tolerance = 2;
var radius = 200;
var particles = [];
for(var i = 0; i < 1000; i++)
{
    particles.push(new create_particle());
}
function create_particle()
{
    this.x = Math.random()*W*2 * (Math.random()<0.5 ? -1 : 1)+W;//Math.random() * (W*2 - W) + W;
    this.y = Math.random()*H*2 * (Math.random()<0.5 ? -1 : 1)+H;//Math.random() * (H*2 - H) + H;
    this.vector_x = (W/2) - this.x;
    this.vector_y = (H/2) - this.y;
    this.distance = Math.sqrt(this.vector_x*this.vector_x + this.vector_y*this.vector_y);
    this.normvector_x = this.vector_x/this.distance;
    this.normvector_y = this.vector_y/this.distance;
    this.vx = Math.random()*20-10;
    this.vy = Math.random()*20-10;
    this.radius = Math.random()*10;
}
function draw()
{
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, W, H);
    for(var t = 0; t < particles.length; t++)
    {
        var p = particles[t];
        ctx.beginPath();
        ctx.fillStyle = "gray";
        ctx.arc(p.x, p.y, p.radius, Math.PI*2, false);
        ctx.fill();
        var distance = Math.sqrt(Math.pow(p.x - W/2, 2) + Math.pow(p.y - H/2, 2));
        var inside =  Math.abs(distance - radius) < tolerance;
        if (!inside) {
            p.x = p.x+ p.normvector_x*7;
            p.y = p.y+ p.normvector_y*7;
        } else {
            if (t%2)
                tolerance+=0.0005;
        }
    }
}
setInterval(draw, 33);
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="600" height="500"></canvas>  
   </body>
</html>

Related Tutorials