业界 作者:SegmentFault 2022-09-13 12:42:58 阅读:874


<link rel="icon" href="xxx.png">
- 网站目录
index.html
favicon.ico

const link = document.querySelector('link[rel~="icon"]');
如果找不到,可以请求/favicon.ico,这里直接添加一个link
function getLink(){
const link = document.querySelector('link[rel~="icon"]');
if (link) {
return link
} else {
const link = document.createElement('link');
link.rel = "icon";
link.href = "/favicon.ico"
document.head.append(link);
return link
}
}
const canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
let dataURL = canvas.toDataURL("image/png");
resolve(dataURL);
canvas = null;
};
img.src = url;
img.onerror = () => {
resolve("默认图base64");
}

<body>
<strong>local</strong>
<img src='xxx.png'>
</body>
strong{
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
text-transform: uppercase;
background-color: orange;
color: #fff;
padding: 0px 2px;
border-radius: 2px;
font-size: 12px;
box-sizing: border-box;
max-width: 100%;
width: max-content;
height: 16px;
line-height: 16px;
word-break: break-all;
overflow: hidden;
}

const link = getLink();
const icon = await img2Base64(link.href);
const favicon = `data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><foreignObject x="0" y="0" width="100%" height="100%"><body xmlns="http://www.w3.org/1999/xhtml">
<style>
html,body{
height: 100%;
margin: 0;
text-align: center;
}
img{
display: block;
width: 100%;
height: 100%;
object-fit: contain;
}
strong{
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
text-transform: uppercase;
background-color: ${color};
color: #fff;
padding: 0px 2px;
border-radius: 2px;
font-size: 12px;
box-sizing: border-box;
max-width: 100%;
width: max-content;
height: 16px;
line-height: 16px;
word-break: break-all;
overflow: hidden;
}
</style>
<strong>local</strong>
这里需要注意几点:
link.href= favicon;

<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
<foreignObject width="100%" height="100%">
<body xmlns="http://www.w3.org/1999/xhtml">
<style>
html,body{
margin: 0;
height: 100%
}
div{
height: 100%;
background: pink;
animation: hue 3s infinite;
}
@keyframes hue {
to {
filter: hue-rotate(360deg)
}
}
</style>
<div></div>
</body>
</foreignObject>
</svg>

