Ефект мерехтіння можна добитися за допомогою приховування/появою елемента через таймер або більш сучасним методом CSS анімацією.
Приклад зміни CSS стиль для появи/приховування елемента за допомогою таймера:
#test
function Shimmer(q){
this.el=document.querySelector(q);
this.animate=function(){
if(this.el.style.visibility=='visible'){
this.el.style.visibility='hidden';
}else{
this.el.style.visibility='visible';
}
setTimeout(this.animate.bind(this), 500);
}
}
var sf=new Shimmer('#test');
sf.animate(); //запуск мерехтіння
CSS анімація дозволяє біль плавно змінювати CSS стилі за допомогою animate().
Мерехтіння елемента canvas на фоні всієї сторінки
Метод start() запускає анімацію, а метод stop() зупиняє її. startTime() запускає анімацію на вказану кількість мілісекунд.
function ShimmerFon(options){
if(options==undefined)options={};
const DEF_OPTIONS={colors:['#5feb0b','#190ee6','#ec7506','#c71209','#000000'], w:10, h:5, alpha:0.75, filling:75};
for(var a in DEF_OPTIONS)options[a]=(a in options?options[a]:DEF_OPTIONS[a]);
//створюємо елемент canvas
this.canvas=document.createElement('canvas');
this.canvas.width=window.innerWidth;
this.canvas.height=window.innerHeight;
this.canvas.style.display='none';
this.canvas.style.position='fixed';
this.canvas.style.zIndex='9999';
this.canvas.style.top='0px';
this.canvas.style.left='0px';
this.animation=null;
document.body.appendChild(this.canvas);
//метод запускає ефект
this.start=function(){
this.canvas.style.display='block';
if(this.animation!=null)this.animation.cancel();
//створюємо анімацію
this.animation=this.canvas.animate([{opacity:1}, {opacity:1}, {opacity:0}, {opacity:0}, {opacity:0}, {opacity:0}, {opacity:1}, {opacity:0}],{duration: 700, iterations:'Infinity'});
}
//метод зупиняє ефект
this.stop=function(){
this.canvas.style.display='none';
this.animation.cancel();
}
//метод запускає ефект на вказаний час
this.startTime=function(ms){
this.start();
setTimeout(this.stop.bind(this), ms);
}
//малюємо на полотні canvas
setTimeout(function(){
var ctx=this.canvas.getContext('2d');
ctx.globalAlpha=options.alpha;
var x=0, y=0;
for(;y<this.canvas.height;){
x=0;
for(var i=0, l=-1;x<this.canvas.width;i++){
if(i>l){
i=0;
l=15*Math.random();
if(100*Math.random()<options.filling)ctx.globalCompositeOperation='destination-out';
else ctx.globalCompositeOperation='source-over';
ctx.fillStyle=options.colors[parseInt(Math.random()*options.colors.length)];
}
ctx.fillRect(x,y,x+options.w, y+options.w);
x+=options.w;
}
y+=options.h;
}
}.bind(this),50);
return this;
}
f=new ShimmerFon();
f.startTime(5500);
Мерехтіння зображення на весь екран
Функція конструктор ShimmerImg приймає параметр src - URL адресу зображення, та створює зображення додаючи його до документу.function ShimmerImg(src){
this.anime=false;
this.img=document.createElement('img');
this.img.src=src;
this.img.style.position='fixed';
this.img.style.top='0px';
this.img.style.left='0px';
this.img.style.width=(outerWidth*parseInt(devicePixelRatio))+'px';
this.img.style.height=(outerHeight*parseInt(devicePixelRatio))+'px';
this.img.style.display='none';
document.body.appendChild(this.img);
this.start=function(){
this.img.style.display='block';
if(this.anime)this.anime.cancel();
this.anime=this.img.animate([{opacity:0.2},{opacity:1},{opacity:0},{opacity:0.5},{opacity:0},{opacity:0},{opacity:0},{opacity:1}],{duration:2000, iterations:'Infinity'});
};
this.stop=function(){
this.img.style.display='none';
this.anime.cancel();
}
this.startTime=function(ms){
ms=parseInt(ms);
this.start();
setTimeout(this.stop.bind(this), ms);
}
}
f2=new ShimmerImg('/_images/glick.png');
f2.startTime(8000);
Ефект мерехтіння елемента
Ефект мерехтіння елемента дозволяє застосувати його до будь якого елемента в документі.Функція конструктор ShimmerElement приймає параметр q - CSS селектор елемента ефект мерехтіння до якого необхідно застосувати.
function ShimmerElement(q){
this.anime=false;
this.el=document.querySelector(q);
if(this.el==null)return false;
this.start=function(){
if(this.anime)this.anime.cancel();
//створюємо анімацію
this.anime=this.el.animate([{opacity:0.2},{opacity:1},{opacity:0},{opacity:0.5},{opacity:0},{opacity:0},{opacity:0},{opacity:1}],{duration:2000, iterations:'Infinity'});
};
this.stop=function(){
this.anime.cancel();
}
this.startTime=function(ms){
this.start();
setTimeout(this.stop.bind(this), ms);
}
}
var f3=new ShimmerElement('body');
f3.startTime(6000); //показати ефект на 8 c