javascript 使用类似于 Gmail 的图像处理的动态图标添加计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6296574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic favicon using image manipulation similar to Gmail adding a count
提问by Santiago
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.
我想知道如何像 Gmail 那样制作一个带有计数的动态图标。
Any idea on how to do this?
关于如何做到这一点的任何想法?
回答by Loktar
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
您可以使用该canvas
元素制作图像,然后只需替换当前的图标。查看以下链接以获得有关它的很好的解释。
参考
Code is from the above reference.
代码来自上述参考。
Markup
标记
<link id="favicon" rel="icon" type="image/png" href="image.png" />
JS
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.
还必须有一个图像集。