飞道的博客

前端读取svg文件 修改svg图标颜色 base64编码图标路径并展示

214人阅读  评论(0)

读取svg文件


  
  1. /**
  2. * 读取svg文件
  3. * @filePath:svg文件路径
  4. */
  5. readFile(filePath) {
  6. // 创建一个新的xhr对象
  7. let xhr = null
  8. if ( window.XMLHttpRequest) {
  9. xhr = new XMLHttpRequest()
  10. } else {
  11. xhr = new ActiveXObject( 'Microsoft.XMLHTTP')
  12. }
  13. const okStatus = document.location.protocol === 'file' ? 0 : 200
  14. xhr.open( 'GET', filePath, false)
  15. xhr.overrideMimeType( 'image/svg+xml')
  16. xhr.send( null)
  17. return xhr.status === okStatus ? xhr.responseText : null
  18. },

根据不同条件修改svg图标颜色


  
  1. // 读取svg文件,修改图标颜色
  2. var title = this.readFile( "../images/测试.svg");
  3. var newSvg;
  4. if(item.id== 1){
  5. newSvg=title.replace( /#(?:[0-9a-fA-F]{6})/g, "#FF0000")
  6. }
  7. if(item.id== 2){
  8. newSvg=title.replace( /#(?:[0-9a-fA-F]{6})/g, "#0000FF")
  9. }
  10. if(item.id== 3){
  11. newSvg=title.replace( /#(?:[0-9a-fA-F]{6})/g, "#FFFFFF")
  12. }
  13. //编码svg图标地址
  14. var svgUrl = 'data:image/svg+xml;base64,' + window.btoa( unescape( encodeURIComponent(newSvg)));

使用svg图标

<img :src="svgUrl" style="width:25px;height:25px;">


转载:https://blog.csdn.net/yangwqi/article/details/104413252
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场