Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

javascript - Dynamic favicon using image manipulation similar to Gmail adding a count

I tried to figure it out looking at the source code but I couldn't figure it out.

I would like to know how to make a dynamic favicon with a count like Gmail does.

enter image description here

Any idea on how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make an image with the canvas element, and then just replace the current favicon. Check out the following link for a good explanation on it. Reference

Code is from the above reference.

Markup

<link id="favicon" rel="icon" type="image/png" href="image.png" /> 

JS

  (function () {
    var canvas = document.createElement('canvas'),
        ctx,
        img = document.createElement('img'),
        link = document.getElementById('favicon').cloneNode(true),
        day = (new Date).getDate() + '';
    
    if (canvas.getContext) {
      canvas.height = canvas.width = 16; // set the size
      ctx = canvas.getContext('2d');
      img.onload = function () { // once the image has loaded
        ctx.drawImage(this, 0, 0);
        ctx.font = 'bold 10px "helvetica", sans-serif';
        ctx.fillStyle = '#F0EEDD';
        if (day.length == 1) day = '0' + day;
        ctx.fillText(day, 2, 12);
        link.href = canvas.toDataURL('image/png');
        document.body.appendChild(link);
      };
      img.src = 'image.png';
    }
    
    })();

Edit

Must have an image set as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...