前端自定义svg怎么显示,一篇文章解决

使用vue3 + vue/cli + element-plus开发项目,icon图标分为两类:

  1. element-plus 的图标
  2. 自定义的 svg 图标,即从iconfont等网站下载的svg图标文件

element-plus 的图标可以直接使用图标名称或者配合 el-icon 显示;
对于自定义图标,则需要一个自定义的组件。

在自定义组件中,需要考虑两种情况:

  1. 显示外部 svg 图标:通过style的mask: url(http://xxx/xxx.svg)

  2. 显示下载到本地的 svg 图标: 通过<svg><use>标签的结合

下面就是自定义icon图标的一个解决方案:

components中创建文件:SvgIcon/index.vue

<template>
  <div
    v-if="isExternal"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    :class="className"
  ></div>
  <svg v-else class="svg-icon" :class="className" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script setup>
import { defineProps, computed } from 'vue'
import { isExternal as external } from '@/utils/validate'
const props = defineProps({
  icon: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ''
  }
})

/**
 * 判断是否为外部图标
 */
const isExternal = computed(() => external(props.icon))

/**
 * 显示外部图标
 */
const styleExternalIcon = computed(() => ({
  mask: `url(${props.icon}) no-repeat 50% 50%`,
  '-webkit-mask': `url(${props.icon}) no-repeat 50% 50%`
}))

/**
 * 显示本地图标
 */
const iconName = computed(() => `#icon-${props.icon}`)
</script>

<style lang="scss" scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: middle;
  fill: currentColor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
  overflow: hidden;
}
.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>

封装isExternal方法:创建 utils/validate.js

//判断是否为外部资源
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

至此外部图标可以正常显示,以下是对于内部图标显示的处理

假设所有的本地图标xxx.svg都放在src/icons/svg目录中

icons下创建index.js文件,用来导入所有图标,并完成自定义组件的全局注册:

require.context函数获取一个特定的上下文,主要用来实现自动化导入模块,在前端工程中,如果遇到从一个文件夹引入很多模块的情况可以使用这个api,它会遍历文件夹中的指定文件,然后自动导入,使得不需要每次显式的调用import导入模块。

require.context函数接受三个参数:

  • directory {String} -读取文件的路径
  • useSubdirectories {Boolean} -是否遍历文件的子目录
  • regExp {RegExp} -匹配文件的正则
import SvgIcon from '@/components/SvgIcon'

// 通过 require.context() 函数来创建自己的 context
const svgRequire = require.context('./svg', false, /\.svg$/)

// 此时返回一个 require 的函数,可以接受一个 request 的参数,用于 require 的导入。
// 该函数提供了三个属性,可以通过 require.keys() 获取到所有的 svg 图标
// 遍历图标,把图标作为 request 传入到 require 导入函数中,完成本地 svg 图标的导入

svgRequire.keys().forEach(svgIcon => svgRequire(svgIcon))

export default app => {
  app.component('svg-icon', SvgIcon)
}

main.js中引入

// 导入 svgIcon
import installIcons from '@/icons'

installIcons(app)

至此图标还没办法显示,需使用svg-sprite-loader ,是 webpack 中专门用来处理 svg 图标的一个 loader

  1. 执行:npm i --save-dev svg-sprite-loader@6.0.9
  2. vue.config.js 文件,新增如下配置:
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = defineConfig({
  chainWebpack(config) {
    // 设置 svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  }
})

现在可以使用了,使用方式如下:

  1. 外部图标:
<span class="svg-container">
	<svg-icon icon="http://xxx/x.svg"></svg-icon>
</span>
  1. 本地图标
<svg-icon icon="user" />
  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在高德地图中使用自定义 SVG 图标,需要进行以下步骤: 1. 准备 SVG 图标文件,并将其命名为 icon.svg。 2. 在 HTML 文件中引入高德地图 API 的 JavaScript 文件,并创建一个空的 div 元素作为地图容器。 ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>高德地图自定义 SVG 图标</title> <script src="https://webapi.amap.com/maps?v=1.4.15&key=您的密钥"></script> <style> #map { width: 100%; height: 500px; } </style> </head> <body> <div id="map"></div> <script> </script> </body> </html> ``` 3. 使用 AMap.Icon 类创建自定义图标对象,并设置图标的大小、位置和 SVG 图标文件路径。 ```html <script> var map = new AMap.Map('map', { center: [116.397428, 39.90923], zoom: 13 }); var icon = new AMap.Icon({ size: new AMap.Size(40, 50), image: "icon.svg", imageOffset: new AMap.Pixel(0, 0), imageSize: new AMap.Size(40, 50) }); var marker = new AMap.Marker({ position: [116.397428, 39.90923], icon: icon, offset: new AMap.Pixel(-20, -50), map: map }); </script> ``` 4. 在 AMap.Icon 对象中,设置 imagePath 属性为 icon.svg 文件所在的目录路径。这样,当使用 icon.svg 图标文件时,高德地图 API 将会从该目录中加载图标文件。 ```html <script> var map = new AMap.Map('map', { center: [116.397428, 39.90923], zoom: 13 }); var icon = new AMap.Icon({ size: new AMap.Size(40, 50), imagePath: "./", image: "icon.svg", imageOffset: new AMap.Pixel(0, 0), imageSize: new AMap.Size(40, 50) }); var marker = new AMap.Marker({ position: [116.397428, 39.90923], icon: icon, offset: new AMap.Pixel(-20, -50), map: map }); </script> ``` 这样,就可以在高德地图中使用自定义 SVG 图标了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值