使用 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>
相关推荐
Nan_Shu_6141 小时前
Web前端面试题(2)
前端
知识分享小能手1 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
2501_918126912 小时前
用html5写一个flappybird游戏
css·游戏·html5
蚂蚁RichLab前端团队2 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光2 小时前
css之一个元素可以同时应用多个动画效果
前端·css
萌萌哒草头将军2 小时前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite
huangql5203 小时前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
Qlittleboy3 小时前
uniapp如何使用本身的字体图标
javascript·vue.js·uni-app
Days20503 小时前
LeaferJS好用的 Canvas 引擎
前端·开源
小白菜学前端3 小时前
vue2 常用内置指令总结
前端·vue.js