Skip to content

Instantly share code, notes, and snippets.

@bowheart
Created October 4, 2016 17:16
Show Gist options
  • Save bowheart/b6fbff9f4e4f94d3633665481e539c3b to your computer and use it in GitHub Desktop.
Save bowheart/b6fbff9f4e4f94d3633665481e539c3b to your computer and use it in GitHub Desktop.
var drawCanvas = function() {
var time,
mouse = {x: 0, y: 0};
var Star = function(ctx, width, height) {
this.ctx = ctx;
this.height = height;
this.width = width;
Math.random() > height / width * .5
? (this.x = parseInt(Math.random() * width)) && (this.y = 0)
: (this.y = parseInt(Math.random() * height)) && (this.x = width);
this.z = Math.random() * 0.8 + 0.2; // range: 0.2 - 1.0
this.speed = this.z * 0.9 + 0.1; // range: 0.1 - 1.0
this.angle = Math.random() * 0.4 + 0.8; // range: 0.9 - 1.1
this.draw();
};
Star.prototype = {
draw: function() { with(this) {
x -= speed * angle;
y += speed * (2 - angle);
ctx.strokeStyle = getColor();
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
} },
getColor: function() { with(this) {
var color = parseInt(z * 255);
return 'rgb(' + [parseInt(color * time * .3), parseInt(color * (1 - time)), color].join(',') + ')';
} }
};
var Animator = function(el) {
this.el = el;
this.ctx = el.getContext('2d');
this.width = el.width;
this.height = el.height;
this.cx = this.width / 2;
this.cy = this.height / 2;
this.stars = [];
this.draw();
};
Animator.prototype = {
draw: function() { with(this) {
time = .5 + .5 * Math.sin(Date.now() / 2000);
if (stars.length < 3 || Math.random() > 0.995 && stars.length < 10) {
stars.push(new Star(ctx, width, height));
}
drawStars();
window.requestAnimationFrame(draw.bind(this));
} },
drawStars: function() { with(this) {
var starsToDelete = [];
stars.forEach(function(star, i) {
star.draw();
if (star.x < 0 || star.y > height) starsToDelete.push(i);
});
starsToDelete.forEach(function(i) {
stars.splice(i, 1);
});
} }
};
var canvas = document.getElementById('canvas');
$(window).resize(function() {
canvas.width = $(this).width();
canvas.height = $(this).height();
}).trigger('resize');
var direction = 0;
var interval = window.setInterval(function() {
switch (direction) {
case 0:
mouse.y += 5;
if (mouse.y >= canvas.height) direction++;
break;
case 1:
mouse.x += 5;
if (mouse.x >= canvas.width) direction++;
break;
case 2:
mouse.y -= 5;
if (mouse.y <= 0) direction++;
break;
case 3:
mouse.x -= 5;
if (mouse.x <= 0) direction++;
break;
default:
window.onmousemove = function(event) {
mouse.x = event.clientX;
mouse.y = event.clientY + $(window).scrollTop();
};
clearInterval(interval);
break;
}
}, 5);
var animator = new Animator(canvas);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment