TolgaTatli / Halve

Stylish Two-Column Jekyll Theme
https://tolgatatli.github.io/Halve/
MIT License
290 stars 357 forks source link

canvas.js improvements #19

Open shellscape opened 8 years ago

shellscape commented 8 years ago

Normally I'd just submit a pull request, but since I've already diverged from the project by quite a bit for my own site, I'm just going to drop this here as an improvement snippet. I've greatly improved the appearance, efficiency, and speed of the canvas.js script for the "snowflake" effect on the homepage. The code as it is on master today will add an exponential amount of Dot objects to the dots.array array - that causes massive memory and cpu spikes. It also appears the script contains a lot of unused/unreachable code, which I've removed.

I hope this code helps to improve Halve.

$(function() {
  'use strict';

  var canvas = document.querySelector('canvas'),
    context = canvas.getContext('2d'),
    color = '#98B232',
    count = 250,
    flakes = [];

  canvas.width = window.innerWidth / 2;
  canvas.height = window.innerHeight;
  canvas.style.display = 'block';

  context.fillStyle = color;
  context.lineWidth = 0.1;
  context.strokeStyle = color;

  for (var i = 0; i < count; i++) {
    flakes.push(new Flake());
  }

  setInterval(animate, 1000 / 30);

  function animate () {
    context.clearRect(0, 0, canvas.width, canvas.height);

    for (var flake of flakes) {
      flake.draw();

      if (flake.y < 0 || flake.y > canvas.height) {
        flake.vx = flake.vx;
        flake.vy = -flake.vy;
      }
      else if (flake.x < 0 || flake.x > canvas.width) {
        flake.vx = -flake.vx;
        flake.vy = flake.vy;
      }
      flake.x += flake.vx;
      flake.y += flake.vy;
    }
  }

  function Flake () {
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;
    this.vx = -.5 + Math.random();
    this.vy = -.5 + Math.random();
    this.radius = Math.random();

    this.draw = function draw () {
      context.beginPath();
      context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
      context.fill();
    }
  }
});
MahdiBaghbani commented 5 years ago

thanks, I did some tests with your version against original file on Firefox and it's really better. good job