Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

faviconを動的に変更する

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)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
6
Help us understand the problem. What are the problem?