Detailed explanation of using SVG to add logo to favicon
Sep 07, 2022 am 10:30 AMHow 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
-?網(wǎng)站目錄 ????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("默認(rèn)圖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 errorDetailed 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 是支持的,為了兼容其他瀏覽器,可以用一個(gè) .ico
來(lái)兜底
<link> <link>
另外,在 Chrome 上還有一個(gè)限制(不知道是不是Chrome 更新后的限制),當(dāng) favicon 使用 svg 格式圖片時(shí),此時(shí)的 svg 會(huì)處于一種secure-static-mode,在這種模式下,所有動(dòng)畫都不會(huì)執(zhí)行,會(huì)處于第一幀,比如下面這個(gè)例子
<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>
很簡(jiǎn)單的一個(gè)背景顏色動(dòng)畫。在 Firefox 上是用作 favicon 是有動(dòng)畫的
但是,Chrome 上卻不行,只有禁止的第一幀
所以之前想實(shí)現(xiàn)標(biāo)識(shí)文本滾動(dòng)的效果可以就此打住了
比較類似的還有媒體查詢,之前在網(wǎng)上看到有這樣的實(shí)現(xiàn),直接在 SVG 中實(shí)現(xiàn)黑暗模式
<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是靜止不動(dòng)的
總的來(lái)說(shuō),SVG 在繪制方面提供了無(wú)限可能,不僅僅是本文中的案例,覺得 canvas 過(guò)于復(fù)雜的都可以考慮這一方案
(學(xué)習(xí)視頻分享: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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

accent-color is an attribute used in CSS to customize the highlight colors of form elements such as checkboxes, radio buttons and sliders; 1. It directly changes the default color of the selected state of the form control, such as changing the blue check mark of the checkbox to red; 2. Supported elements include input boxes of type="checkbox", type="radio" and type="range"; 3. Using accent-color can avoid complex custom styles and extra DOM structures, and maintain native accessibility; 4. It is generally supported by modern browsers, and old browsers need to be downgraded; 5. Set accent-col

InstallDartSassvianpmafterinstallingNode.jsusingnpminstall-gsass.2.CompileSCSStoCSSusingthecommandsassinput.scssoutput.css.3.Usesass--watchinput.scssoutput.csstoauto-compileonsave.4.Watchentirefolderswithsass--watchscss:css.5.Usepartialswith_prefixfo

To change the text color in CSS, you need to use the color attribute; 1. Use the color attribute to set the text foreground color, supporting color names (such as red), hexadecimal codes (such as #ff0000), RGB values (such as rgb(255,0,0)), HSL values (such as hsl(0,100%,50%)), and RGBA or HSLA with transparency (such as rgba(255,0,0,0.5)); 2. You can apply colors to any element containing text, such as h1 to h6 titles, paragraph p, link a (note the color settings of different states of a:link, a:visited, a:hover, a:active), buttons, div, span, etc.; 3. Most

CSStransitionsenablesmoothpropertychangeswithminimalcode,idealforhovereffectsandinteractivefeedback.1.Usethesyntaxtransition:propertydurationtiming-functiondelay;todefinetransitions,liketransition:background-color0.3sease0.1s;.2.Specifytransition-pro

UseautomatedtoolslikePurgeCSSorUnCSStoscanandremoveunusedCSS;2.IntegratepurgingintoyourbuildprocessviaWebpack,Vite,orTailwind’scontentconfiguration;3.AuditCSSusagewithChromeDevToolsCoveragetabbeforepurgingtoavoidremovingneededstyles;4.Safelistdynamic

Astackingcontextisaself-containedlayerinCSSthatcontrolsthez-orderofoverlappingelements,wherenestedcontextsrestrictz-indexinteractions;itiscreatedbypropertieslikez-indexonpositionedelements,opacity

In web development, the choice of CSS units depends on design requirements and responsive performance. 1. Pixels (px) are used to fix sizes such as borders and icons, but are not conducive to responsive design; 2. Percentage (%) is adjusted according to the parent container, suitable for streaming layout but attention to context dependence; 3.em is based on the current font size, rem is based on the root element font, suitable for elastic fonts and unified theme control; 4. Viewport units (vw/vh/vmin/vmax) are adjusted according to the screen size, suitable for full-screen elements and dynamic UI; 5. Auto, inherit, initial and other values are used to automatically calculate, inherit or reset styles, which helps to flexibly layout and style management. The rational use of these units can improve page flexibility and responsiveness.

TheCSSfilterpropertyappliesvisualeffectstoelementsdirectlyinCSS,withcommonusesincluding:1.blur()forsofteningimagesorcreatingdepth,2.brightness()toadjustlightnessordarkness,3.contrast()toenhanceorreducevisualdistinction,4.grayscale()forblack-and-white
