Canvas animation with JavaScript with Random coordinates and speed at every initiation - Javascript Canvas

Javascript examples for Canvas:Animation

Description

Canvas animation with JavaScript with Random coordinates and speed at every initiation

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Canvas ball animation with random coordinates and speed</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/random-js/1.0.8/random.js"></script> 
      <style id="compiled-css" type="text/css">

#canv {//from  www . j ava 2s .c o m
   display: block;
   border: 2px solid pink;
   margin: 0 auto;
}


      </style> 
      <script type="text/javascript">
    window.onload=function(){
var canv = document.getElementById('canv');
var randEngine = Random.engines.mt19937().autoSeed();
var rand = function(from, to){
  return Random.integer(from, to)(randEngine)
}
var ctx = canv.getContext('2d');
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
var width = window.innerWidth;
var height = window.innerHeight;
function sanitizer(l) {
  if(l % 100) return l - (l%100);
}
canv.width = width = sanitizer(width);
canv.height = height = sanitizer(height);
console.log(width, height);
var circles = [];

for(var i = 50; i <= width; i += 10)
  for(var j = 50; j <= height; j += 10)
   circles.push({
    coords: {x:i,y:j}
   });
var offset = 15,
    speed = 0.001,
    angle = 0.01,
    bouncing = 15;
function setBaseRgb(el){
  el.base = rand(-bouncing, bouncing);
  el.speed = rand(5, 10) * speed;
  el.angle = 0;
  el.rgb = 'rgb('+rand(0, 255)+','+rand(0, 255)+','+rand(0, 255)+')';
}
circles.forEach(function(el){
  setInterval(setBaseRgb.bind(null,el), rand(3000, 5000));
});
function render() {
  ctx.clearRect(0,0,width,height);
  circles.forEach(function(el) {
    ctx.fillStyle = el.rgb;
    ctx.beginPath();
    var r = bouncing + el.base + Math.abs(Math.sin(el.angle)) * offset;
    console.log(el.angle);
    var coords = el.coords;
    ctx.arc(
       coords.x + el.base,
       coords.y + el.base,
       r, 0, Math.PI * 2, false
    );
    ctx.fill();
     el.angle += el.speed;
    if(el.angle > 1)
      el.angle=0;
  });
  requestAnimationFrame(render);
}
render();
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canv"></canvas>  
   </body>
</html>

Related Tutorials