Ефект мерехтіння

ПублікаціїАнімації і ефекти

Ефект мерехтіння можна добитися за допомогою приховування/появою елемента через таймер або більш сучасним методом 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 на фоні всієї сторінки

Функція конструктор ShimmerFon створює елемент canvas та додає його до документу. canvas буде відображатися поверх всієї сторінки. Також функція малює на полотні прямокутні ліній. Функція може приймати параметри: colors - кольори ліній, w - ширина, h - висота, alpha - прозорість canvas від 0 до 1, filling - відсоток заповнення лініями полотна від 0 до 100.

Метод 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
Адмін 2020-03-28 21:15:05
Коментарів 3
Alsk Alsk # 2021-07-31 14:03:03
Мерехтіння елемента canvas на фоні всієї сторінки
Alsk Alsk # 2021-07-31 14:50:04
"підвішує" всю систему. У мене лінукс кде. Перезапускаються ефекти робочого столу. Але перед цим процесор кілька секунд торохтить (сильно навантажується).
Адмін # 2021-08-19 05:45:53
Навантаження виникає при малюванні на полотні canvas.

Тільки зареєстровані користувачі можуть писати коментарі.