Home >Web Front-end >CSS Tutorial >Detailed explanation of using SVG to add logo to favicon

Detailed explanation of using SVG to add logo to favicon

青灯夜游
青灯夜游forward
2022-09-07 10:30:161829browse

How to use SVG to add a logo to favicon? The following article will introduce to you how to use SVG to generate favicon with logo. I hope it will be helpful to you!

I made a Chrome plug-in before, which can generate different icons according to different addresses. This can easily distinguish different development environments. The effect is as follows

The main implementation process is actually not complicated. First, obtain the website favicon, then add a logo to the favicon, and then redraw and generate it.

Among them, The icons here are generated through SVG. Let’s take a look at the specific implementation. [Recommended learning: css video tutorial]

1. How to obtain the favicon

If you want to know how to obtain it, you can first understand the setting method.

Generally there are two ways to set the favicon of the website.

The first one is set through the link tag (requires the rel="icon" attribute)

<link>

The second one is directly in the Website root directoryPut a favicon.ico (must be this name, the browser defaults), there is no need to set anything in the html

- 网站目录
    index.html
    favicon.ico

If none of the above are set, Then there is a high probability that you will see the following error

Understanding these, obtaining it is simple. First obtain it through link, as long as rel Just include icon

const link = document.querySelector('link[rel~="icon"]');

If you can’t find it, you can request /favicon.ico, and add a 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
    }
}
directly here

The link obtained in this way is guaranteed to exist, and then it is drawn

2. Use canvas to draw

Since the image needs to be synthesized, So you need to draw the original image first. When it comes to image drawing, you can think of canvas drawing, and only a little basic knowledge of canvas is enough. The specific implementation is as follows

const canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
Detailed explanation of using SVG to add logo to favicon = new Image();
Detailed explanation of using SVG to add logo to favicon.crossOrigin = 'anonymous';
Detailed explanation of using SVG to add logo to favicon.onload = () => {
    canvas.height = Detailed explanation of using SVG to add logo to favicon.height;
    canvas.width = Detailed explanation of using SVG to add logo to favicon.width;
    ctx.drawImage(Detailed explanation of using SVG to add logo to favicon, 0, 0, canvas.width, canvas.height);
    let dataURL = canvas.toDataURL("image/png");
    resolve(dataURL);
    canvas = null;
};
Detailed explanation of using SVG to add logo to favicon.src = url;

Since there is no setting in /favicon.ico, it is necessary to give a default image when the Detailed explanation of using SVG to add logo to favicon fails to load

Detailed explanation of using SVG to add logo to favicon.onerror = () => {
    resolve("默认图base64");
}

This way Obtained the image information of the favicon

3. Use SVG for image synthesis

Based on the above, you can actually continue to draw through canvas and draw a label It's not difficult either. However, SVG can be used to draw here, which has the following advantages

  • Lower cost and easier to understand than canvas

  • High flexibility , you can perform some style control through CSS

First of all, we can freely draw such a layout in HTML like normal web development, I believe it is not difficult

  <strong>local</strong>
  <detailed explanation of using svg to add logo favicon>
</detailed>

Due to the limited width, it is necessary to force the text to wrap beyond hiding. The key style is as follows

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;
}

Next, put this piece of html into the foreignObject tag Regarding the role of foreignObject, those who are interested can refer to this article by Zhang Xinxu about SVG introduction and screenshots. Here, you can simply understand that it can contain HTML tags, and SVG itself is also a kind of picture, so The purpose of synthesizing images has been achieved

The specific implementation is as follows

const link = getLink();
const icon = await Detailed explanation of using SVG to add logo to favicon2Base64(link.href);
const favicon = `data:image/svg+xml;charset=utf-8,<svg><foreignobject>
  <style>
    html,body{
      height: 100%;
      margin: 0;
      text-align: center;
    }
    Detailed explanation of using SVG to add logo to favicon{
      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>
  <detailed explanation of using svg to add logo favicon></detailed>explanation of using SVG to add logo to favicon>
  </foreignobject></svg>`.replace(/\n/g, '').replace(/\t/g, '').replace(/#/g, '%23')

There are several points to note here

  • Detailed explanation of using SVG to add logo to favicon tag In svg, it needs to be written in the closed form <detailed explanation of using svg to add logo favicon></detailed>explanation of using SVG to add logo to favicon>, otherwise it will be considered a structural error

  • Detailed explanation of using SVG to add logo to favicon Only inline images can be used, such as base64, which is why the original favicon is drawn

  • If you use inline svg, you need to escape the svg

  • In the string You also need to pay attention to the issue of single and double quotation marks

Then, set the generated SVG directly to the favicon

link.href= favicon;

and it will work normally Rendered~

For complete implementation, please refer to the project: https://github.com/XboxYan/auto-dev-favicon-chrome-plugin

四、一些局限性

首先是兼容性。

目前只有 Chrome 和 Firefox 是支持的,为了兼容其他浏览器,可以用一个 .ico来兜底

<link>
<link>

另外,在 Chrome 上还有一个限制(不知道是不是Chrome 更新后的限制),当 favicon 使用 svg 格式图片时,此时的 svg 会处于一种secure-static-mode,在这种模式下,所有动画都不会执行,会处于第一帧,比如下面这个例子

<svg>
  <foreignobject>
      
        <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>
      
    </foreignobject>
</svg>

很简单的一个背景颜色动画。在 Firefox 上是用作 favicon 是有动画的

但是,Chrome 上却不行,只有禁止的第一帧

所以之前想实现标识文本滚动的效果可以就此打住了

比较类似的还有媒体查询,之前在网上看到有这样的实现,直接在 SVG 中实现黑暗模式

<svg>
    <style>
        path {
            fill: #fff;
        }
        rect {
            fill: #B09AFE;
        }
        @media (prefers-color-scheme: dark) {
            path {
                fill: #B09AFE;
            }
            rect {
                fill: #fff;
            }
        }
    </style>
    <rect></rect>
    <path></path>
</svg>

但是也是同样的问题,只有 Firefox 下可行,Chrome是静止不动的

总的来说,SVG 在绘制方面提供了无限可能,不仅仅是本文中的案例,觉得 canvas 过于复杂的都可以考虑这一方案

(学习视频分享:web前端

The above is the detailed content of Detailed explanation of using SVG to add logo to favicon. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete