Edited at

faviconを動的に変更する

More than 1 year has passed since last update.

faviconが回転しているサイトを見つけたので備忘録

https://umabi.jp/poputepi-kinen/assets/js/favicon.js


favicon.js

(function(){

var favicons = [
'/favicon_1.png',
'/favicon_2.png',
'/favicon_3.png',
'/favicon_4.png'
];
var favicons_base64 = [];
var counter = 0;
var elms = [];
var head = document.getElementsByTagName('head')[0];
var FPS = 200;
var STAGE_SIZE = 64; // 画像サイズ

var canvas = document.createElement('canvas');
canvas.width = STAGE_SIZE;
canvas.height = STAGE_SIZE;
var context = canvas.getContext('2d');

function main(){
setBase64ToArray( counter );
}

function setBase64ToArray( n ){
var img = new Image();
img.onload = function(){
context.drawImage(img, 0, 0);
var base64 = canvas.toDataURL('image/png');
favicons_base64.push(base64);
if(n === favicons.length - 1){
canvas = null;
context = null;
counter = 0;
animateFavicon();
}else{
n++;
context.clearRect(0, 0, STAGE_SIZE, STAGE_SIZE)
setBase64ToArray( n );
}
};

img.src = favicons[ n ] + '?' + new Date().getTime();
}

function animateFavicon(){
setInterval( function(){
changeFavicon();
}, FPS);
}

function changeFavicon(){
elms = document.getElementsByTagName('link');
for(var i = 0, cnt = elms.length; i < cnt; i++){
if(elms[i].getAttribute('rel')){
if(elms[i].getAttribute('rel') === 'icon'){
// console.log(elms[i]);
elms[i].setAttribute('href', favicons_base64[counter]);

if(counter === favicons.length - 1){
counter = 0;
}else{
counter++;
}
}
}
}
}

window.addEventListener('load', function(){
var ua = window.navigator.userAgent.toLowerCase();
if(ua.indexOf('trident') >= 0 || ua.indexOf('edge') >= 0 || ua.indexOf('iphone') >= 0 || ua.indexOf('android') >= 0 || ua.indexOf('ipad') >= 0) return;
main();
}, false);

})();



参考

JavaScript で faviconを動的に変更する

faviconを動的に変更する(html5-canvas)