使用 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>
相关推荐
Jiaberrr6 分钟前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho1 小时前
【TypeScript】知识点梳理(三)
前端·typescript
安冬的码畜日常2 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
太阳花ˉ2 小时前
html+css+js实现step进度条效果
javascript·css·html
小白学习日记2 小时前
【复习】HTML常用标签<table>
前端·html
john_hjy3 小时前
11. 异步编程
运维·服务器·javascript
风清扬_jd3 小时前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome
丁总学Java3 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
yanlele3 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范