search
HomeWeb Front-endCSS TutorialDetailed explanation of using SVG to add logo to favicon

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. If there is any infringement, please contact admin@php.cn delete
巧用CSS实现各种奇形怪状按钮(附代码)巧用CSS实现各种奇形怪状按钮(附代码)Jul 19, 2022 am 11:28 AM

本篇文章带大家看看怎么使用 CSS 轻松实现高频出现的各类奇形怪状按钮,希望对大家有所帮助!

5个常见的JavaScript内存错误5个常见的JavaScript内存错误Aug 25, 2022 am 10:27 AM

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

实战:vscode中开发一个支持vue文件跳转到定义的插件实战:vscode中开发一个支持vue文件跳转到定义的插件Nov 16, 2022 pm 08:43 PM

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

Node.js 19正式发布,聊聊它的 6 大特性!Node.js 19正式发布,聊聊它的 6 大特性!Nov 16, 2022 pm 08:34 PM

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

浅析Vue3动态组件怎么进行异常处理浅析Vue3动态组件怎么进行异常处理Dec 02, 2022 pm 09:11 PM

Vue3动态组件怎么进行异常处理?下面本篇文章带大家聊聊Vue3 动态组件异常处理的方法,希望对大家有所帮助!

聊聊如何选择一个最好的Node.js Docker镜像?聊聊如何选择一个最好的Node.js Docker镜像?Dec 13, 2022 pm 08:00 PM

选择一个Node​的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

聊聊Node.js中的 GC (垃圾回收)机制聊聊Node.js中的 GC (垃圾回收)机制Nov 29, 2022 pm 08:44 PM

Node.js 是如何做 GC (垃圾回收)的?下面本篇文章就来带大家了解一下。

【6大类】实用的前端处理文件的工具库,快来收藏吧!【6大类】实用的前端处理文件的工具库,快来收藏吧!Jul 15, 2022 pm 02:58 PM

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft