Skip to content

SVG

SVG 在既能满足现有图片的功能的前提下,又是矢量图,在可访问性上面也非常不错,并且有利于 SEO 和无障碍,在性能和维护性方面也比 icon font 要出色许多

  • SEO 设置 title 与 desc 标签

渲染性能

一些效果需要在用户电脑展示时计算

缺点:

  • 小程序目前不支持 SVG 标签,仅仅支持加载 SVG 之后 作为 background-image 进行展示,如 background-image: url("data:image/svg+xml.......),或者 base64 后作为 background-image 的 url。

浏览器渲染 svg 的性能一般,还不如 png。 Iconfont-阿里巴巴矢量图标库

为什么要用 SVG?- svg 与 iconfont、图片多维度对比 - 云+社区 - 腾讯云Delivering Octicons with SVG - The GitHub Blog

应用

  • 绝大部分场景推荐使用 img 方式
  • 预载页面时使用 inline 方式,因为可立即展示

The Best Way to Embed SVG on HTML (2019)

css
.icon_no-content {
  width: 119px;
  height: 93px;
  background-image: url('~@/assets/images/no-content.svg');
  background-repeat: no-repeat;
}

对比 iconfont

  • hack
  • 不支持多色
  • 闪动
  • 维护麻烦

Iconfont 字体生成原理及使用技巧 Iconfont-阿里巴巴矢量图标库

处理

SVG精简压缩工具svgo简介和初体验 « 张鑫旭-鑫空间-鑫生活SVG 高性能优化清单 - 前端 - 掘金

改变颜色

  1. 使用 inline svg in html

做点:最简单 缺点:需要写 HTML code 兼容性:IE9+

scss
.foo {
    &:hover {
        color: #0065DD;
        cursor: pointer;
        svg path {
            fill: currentcolor;
            // stoke: currentcolor;
        }
    }
}
  1. svg loader

基础

arc 弧
rect 矩形
storke 划,击

HTML中嵌入SVG图片的N种方式 - 北月武馆 - SegmentFault 思否Use React SVG components for icons instead of an icon font · Issue #10353 · ant-design/ant-design

路径动画

line 888
storke-dasharray:888
stroke-dashoffset:888
css
  from {
    stroke-dashoffset: 2242.58740234375;
  }
  to {
    stroke-dashoffset:0;
  }

线性渐变

svg
  defs
    linearGradient

当一个程序员对算法、语言标准、底层、原生、英文文档这些词汇产生恐惧感的时候,他的技术生命已经走到尽头