Clouds

Using requestAnimationFrame

by Chris

HTML

<canvas id="canvas" width="500" height="500"></canvas>

CSS

body {
  background-color: #333;
}

canvas {
  border: solid 1px #000;
}
}

JavaScript

function init() {
  draw();
}
var x = 0;
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');


let particles = [];
// Generate 100 particles with random positions
for(i = 0; i < 1000; i++) {
	particles[i] = {
  	x: ranInt(0, c.width),
    y: ranInt(0, c.height),
  }
}

function draw() {

	ctx.clearRect(0, 0, c.width, c.height);
  // Dark blue for water
  ctx.fillStyle = "#093b8c";
  
  ctx.globalAlpha = 1;
 	ctx.fillRect(0, 0, c.width, c.height)
  
  // Gray color for cloud
	ctx.fillStyle = "#aaa";
  for(p in particles) {
      if(particles[p].x > c.width) {
      	particles[p].y = ranInt(0,c.width);
        particles[p].x = 0;
      } else {
  			particles[p].x += 1;
      }
      ctx.globalAlpha = 0.01;
  	//ctx.fillRect(particles[p].x,particles[p].y,15,15);  
    ctx.beginPath();
    ctx.arc(particles[p].x, particles[p].y, ranInt(45,50), 0, 2 * Math.PI);
    ctx.fill();
  }
  
 window.requestAnimationFrame(draw);
}

// Return a random integer within provided range
function ranInt(min, max) {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min + 1)) + min;
}

init();