Dynamically generated favicon

后端 未结 4 2053
有刺的猬
有刺的猬 2020-12-07 10:21

Would it be possible using only JavaScript and HTML to dynamically generate a favicon, using the current page\'s favicon as a background, and a random number in the foregrou

相关标签:
4条回答
  • 2020-12-07 10:36

    favicon.js does exactly this. This library can display a counter in the bottom right corner of the favicon, among other features.

    0 讨论(0)
  • 2020-12-07 10:39

    EDIT: Got it working with

    var canvas = document.createElement('canvas');
        canvas.width = 16;canvas.height = 16;
        var ctx = canvas.getContext('2d');
        var img = new Image();
        img.src = '/favicon.ico';
        img.onload = function() {
            ctx.drawImage(img, 0, 0);
            ctx.fillStyle = "#F00";
            ctx.fillRect(10, 7, 6, 8);
            ctx.fillStyle = '#FFFFFF';
            ctx.font = 'bold 10px sans-serif';
            ctx.fillText('2', 10, 14);
    
            var link = document.createElement('link');
            link.type = 'image/x-icon';
            link.rel = 'shortcut icon';
            link.href = canvas.toDataURL("image/x-icon");
            document.getElementsByTagName('head')[0].appendChild(link);
        }
    

    You can actually run chrome and paste this:

    javascript: var canvas = document.createElement('canvas');canvas.width = 16;canvas.height = 16;var ctx = canvas.getContext('2d');var img = new Image();img.src = '/favicon.ico';img.onload = function() {ctx.drawImage(img, 0, 0);ctx.fillStyle = "#F00";ctx.fillRect(10, 7, 6, 8);ctx.fillStyle = '#FFFFFF';ctx.font = 'bold 10px sans-serif';ctx.fillText('2', 10, 14);var link = document.createElement('link');link.type = 'image/x-icon';link.rel = 'shortcut icon';link.href = canvas.toDataURL("image/x-icon");document.getElementsByTagName('head')[0].appendChild(link);}
    

    into the browser and see it in action.

    enter image description here

    0 讨论(0)
  • 2020-12-07 10:39

    I don't know about doing it all in the browser, but it would be easy to have a server endpoint that accepted parameters in the URL and returned a composed favicon. Then Javascript could modify the favicon url to get the image it wanted.

    0 讨论(0)
  • 2020-12-07 10:50

    You might take a look at this question, which discusses how to change the favicon dynamically. Also here is a site that claims to play a game in the favicon using only JavaScript, canvas, and the data URI, which should work in all modern browsers except IE. Not sure if that would fulfill your requirements or not, but you can try reverse engineering how it works.

    Here's an SO answer that explains how to use the canvas element to read the favicon data and get the image data out, which then can be modified and composed into a new icon.

    0 讨论(0)
提交回复
热议问题