GMail(带有"未读邮件图标" Labs扩展程序)和PagerDuty都会在Chrome标题选项卡中显示的图标上显示通知计数。
如何让我的网页也这样做?
答案 0 :(得分:2)
这很简单。您基本上使用canvas元素“绘制”图标并在其上写入文本,然后将生成的图像作为数据URI并将其设置为您的页面图标。
例如:
window.onload = function(){
var unreadEmails = 8; // Just an example
var canvas = document.getElementById("my-canvas");
var favicon = document.getElementById("my-favicon");
canvas.width = 16; // Favicons are usually 16x16
canvas.height = 16;
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
// When the <img> is loaded, draw it into the canvas
context.drawImage(imageObj, 0, 0);
// Setup an small font size for the text and draw it over the icon image
context.font = "11px sans-serif";
context.fillText(unreadEmails, 4, 4);
// Finally get result as an base64 encoded png
var modifiedIcon = canvas.toDataURL();
// And set it as the href of your favicon tag
favicon.href = modifiedIcon;
};
imageObj.src = "my-favicon-16-px.png";
};
<html>
<head>
<link id="my-favicon" rel="shortcut icon" href="my-favicon-16-px.png">
</head>
<body>
<!-- hidden because it's just used to render the icon with the text -->
<canvas id="my-canvas" style="display:none;">
</body>
</html>
显然,这段代码需要进行一些调整才能得到理想的结果。但它足以让你了解他们是如何做到的。
有些网站甚至更进一步,并使用favicon作为用户界面的一部分。例如MixCloud,在favicon上显示当前的播放状态(按播放以查看其运行情况)。