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
288 views
in Technique[技术] by (71.8m points)

javascript - Dynamically generated favicon

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 foreground?

For example, lets say the current favicon looks similar to this:

======================
====XXXXXXXXXXXXXX====
====X=================
====X=================
====X=====XXXXXXXX====
====X============X====
====X============X====
====XXXXXXXXXXXXXX====
======================

If possible, how would I get it to look something similar to this using only JavaScript and HTML:

======================
====XXXXXXXXXXXXXX====
====X=================
====X=================
====X=====XXXXXXXX====
====X=========--111--=
====X=========--1-1--=
====XXXXXXXXXX----1--=
==============--1111-=

map:
= : white background
x : Original Favicon image
- : Red generated image with a number
1 : White text

Ideas:

  • Canvas?
  • Data Uri's?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


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

...