使用 js 动态修改在线 svg 背景色

使用 js 动态修改在线 svg 背景色

由于网上搜了很多相关资料,都是介绍如何通过 js 修改本地 svg 资源。不过我们要求是要修改在线 svg 资源,因此,在一顿研究之后,封装了如下组件。

js 复制代码
<template>
  <img v-if="url" class="hyl-svg-container" :src="url"/>
</template>

<script>
  export default {
    name: 'hyl-svg-container',
    props: {
      src: String,
      fill: String,
      options: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        content: '',
        url: ''
      };
    },
    watch: {
      fill: {
        handler(v) {
          if (this.content && v) {
            this.fillColor();
          }
        },
        immediate: true
      }
    },
    created() {
      this.fetchSvgSource();
    },
    methods: {
      async fetchSvgSource() {
        if (!this.src) return;
        const response = await fetch(this.src);
        const contentType = response.headers.get('content-type');
        const [fileType] = (contentType || '').split(/ ?; ?/);
		// 异常状态
        if (response.status > 299) {
          console.error('Not found');
        }
        this.url = '';
		// 非有效格式
        if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {
          console.error(`Content type isn't valid: ${fileType}`);
          this.url = this.src;
          return;
        }
        // 获取内容
        const content = await response.text();
        this.content = content;
        this.fillColor();
      },
      fillColor() {
        if (this.fill) {
          // 支持自定义填充颜色
          this.content = this.content.replace(/#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/g, this.fill);
        }
        // 转换base64
        const base64Code = btoa(this.content);
        const base64SVG = `data:image/svg+xml;base64,${base64Code}`;
        this.url = base64SVG;
      }
    }
  };
</script>

<style>
.hyl-svg-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
相关推荐
HashTang15 小时前
不用再配服务器了!这套 Next.js + Cloudflare 模板,一个人搞定全栈出海
前端·后端·边缘计算
Cory.眼15 小时前
WebRTC入门指南:实时通信零基础
javascript·webrtc·实时通信
前端架构师-老李16 小时前
16 Electron 应用自动更新方案:electron-updater 完整指南
前端·javascript·electron
一只学java的小汉堡16 小时前
HTML 01入门:从概念到开发环境搭建与页面头部配置
前端·css·html
拖拉斯旋风16 小时前
📚 JavaScript 变量声明三剑客:`var`、`let`、`const` 学习笔记
javascript
用户214965158987516 小时前
从零搭建uniapp环境-记录
前端
可触的未来,发芽的智生18 小时前
追根索源:换不同的词嵌入(词向量生成方式不同,但词与词关系接近),会出现什么结果?
javascript·人工智能·python·神经网络·自然语言处理
努力写代码的熊大18 小时前
stack、queue与priority_queue的用法解析与模拟实现
java·前端·javascript
im_AMBER18 小时前
React 06
前端·javascript·笔记·学习·react.js·前端框架
wyzqhhhh18 小时前
前端常见的设计模式
前端·设计模式