Skip to content
This repository has been archived by the owner on Mar 14, 2024. It is now read-only.

canvas.js improvements #19

Open
shellscape opened this issue Aug 24, 2016 · 1 comment
Open

canvas.js improvements #19

shellscape opened this issue Aug 24, 2016 · 1 comment

Comments

@shellscape
Copy link

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
Copy link

MahdiBaghbani commented Jun 28, 2019

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants