Ефект ночі досягнемо за допомогою елемента canvas який розміщуємо поверху всіх елементів.
В області курсора малюємо коло за допомогою метода arc(). Щоб було видно веб-сторінку задамо прозоре коло, для цього необхідно задати параметр globalCompositeOperation значення 'destination-out'.
Щоб ефект затемнення був створений поступово створимо анімацію елемента canvas за допомогою метода Element.animate().
function TemnaNich(a){
this.options={timeBlack:5500, radius:50};
for(var b in a)if(b in this.options)this.options[b]=a[b];
this.canvas=document.createElement('canvas');
this.ctx=this.canvas.getContext('2d');
this.clear=function(){
this.ctx.globalCompositeOperation='source-over';
this.ctx.shadowBlur=0;
this.ctx.fillStyle='black';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
this.show=function(time){
if(time){
setTimeout(this.show.bind(this),time,);
return false;
}
this.body=document.documentElement;
this.body.appendChild(this.canvas);
this.canvas.width=this.body.clientWidth;
this.canvas.height=this.body.clientHeight;
window.addEventListener('resize', function(){
this.canvas.width=this.body.clientWidth;
this.canvas.height=this.body.clientHeight;
}.bind(this));
this.canvas.style.position="fixed";
this.canvas.style.top=0;
this.canvas.style.left=0;
this.canvas.style.padding=0;
this.canvas.style.margin=0;
this.canvas.style.zIndex=999;
this.clear();
if(this.canvas.animate)this.canvas.animate([{opacity:0},{opacity:1}], {duration:this.options.timeBlack, fill: 'forwards'});
this.canvas.onmousemove=function(e){ //переміщення курсора
this.clear();
this.ctx.globalCompositeOperation='destination-out';
this.ctx.shadowBlur=25;
this.ctx.shadowColor='white';
this.ctx.fillStyle='white';
this.ctx.beginPath();
this.ctx.arc(e.x+50, e.y+50, this.options.radius, 0, 2*Math.PI); //малюємо коло в області курсора
this.ctx.fill();
}.bind(this);
}
}
var t = new TemnaNich( {timeBlack:5000, radius: 75} );
t.show(3000); //показуємо ефект ночі через 3 секунди