sgon00
sgon00

Reputation: 5777

How to create Particles Webpage Background without animation (pure css)

I'd like to have some particles like what it looks like in particles.js, but without any animations and with pure CSS code. I know this can be done, but I can not find any example or tutorial online how to achieve it. The animation part is annoyed for both css-solution and js-solution because of high CPU usage. So I am trying to find a way to remove animation and use pure css for better performance.

Thanks a lot.

Edited: maybe a lightweight javascript version is fine too as long as it's lightweight.

Upvotes: 1

Views: 1099

Answers (1)

Davi
Davi

Reputation: 4147

You can use the compiled CSS from your second example and remove everything in it which is there for animation purposes.

In case you don't mind a (small) JavaScript based solution, see below. It uses the <canvas> element to draw particles:

(function (runModule) {
  // init. renders 200 particles into the element with ID "bg".
  // particles have a radius between 3 and 9px (6 +- 3) and
  // can either be red, blue or green
  runModule(document.querySelector('#bg'), 200, 6, [
    '#c00',
    '#0c0',
    '#00c'
  ]);
})(function (canvas, particleCount, particleRadius, particleColors) {
  var ctx = canvas.getContext('2d');
  var particles = [];
  var particle;
  
  create();
  render();
  
  window.addEventListener('resize', resize);
  
  function makeParticle (radius, colors) {
    return {
      x: between(radius, canvas.width - radius),
      y: between(radius, canvas.height - radius),
      r: between(radius * 0.5, radius * 1.5),
      c: colors[Math.floor(Math.random() * colors.length)]
    };
  }

  function create () {
    particles = [];
    while (particles.length < particleCount) {
      particle = makeParticle(particleRadius, particleColors);
      particles.push(particle);
    }
  }
  
  function render () {
  	ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  	particles.forEach(function (particle) {
    	ctx.beginPath();
    	ctx.arc(particle.x, particle.y, particle.r, 0, Math.PI * 2);
    	ctx.closePath();
    	ctx.fillStyle = particle.c;
    	ctx.fill();
    })
  }
    
  function resize () {
    var rect = canvas.parentNode.getBoundingClientRect();
    canvas.width = rect.width;
    canvas.height = rect.height;
    create();
    render();
  }
  
  function between (a, b) {
    return Math.round(Math.max(a, Math.random() * b));
  }
});
#bg {
  background: #000;
}
<canvas id="bg" width="320" height="200"></canvas>

Upvotes: 2

Related Questions