小程序展示后端传来的svg图 是通过 image 标签引入 还是别的方法?

发布于 8 年前作者 zougang6164 次浏览最后编辑 8 年前来自 ask

是通过 image 标签引入 还是有别的方法直接展示

3 回复
chenglei
chenglei1 楼6 年前

传回来的是什么?截个图看看

请学会如何「提问」(👈戳我)

qianming
qianming2 楼6 年前

直接拿到svg的url使用 image组件来显示就可以了

idu
idu3 楼6 年前

你这接口返回内容不止svg标签呀

可以将svg标签提取出来,转为base64数据,最终替换成<img src="src=“data:image/svg+xml;base64,…” />

// strHtml为接口返回的html内容
initContent: function(strHtml) {
    var t = this, fs = wx.getFileSystemManager(), ps = []
    t.svgTags = {}
    t.contentParts = strHtml.split(/(<svg[^>]+>(?:(?!<\/svg>).)*<\/svg>)/g)
    for (var i in t.contentParts) {
      if (/<svg/.test(t.contentParts[i])) {
        t.svgTags[i] = { svg: t.contentParts[i], src: '', file: `${wx.env.USER_DATA_PATH}/svg_${i}` + '.svg' }
        ps.push((function (k, o, fs) {
          var file = o.svgTags[k].file
          return new Promise((rs, rj) => {
            fs.writeFile({
              filePath: file,
              data: o.svgTags[k].svg,
              success(res) {
                o.svgTags[k].src = 'data:image/svg+xml;base64,' + fs.readFileSync(file, 'base64')
                rs(res)
              },
              fail(res) {
                console.log(res)
                rj(res)
              }
            })
          })
        })(i, t, fs))
      }
    }
    console.log(ps)
    ps.length && Promise.all(ps).then(res => {
      console.log(t.svgTags)
      for(var i in t.svgTags){
        t.contentParts[i] = '<img style="width:100%;height:auto;border:0;" src="' + t.svgTags[i].src + '" />'
      }
      // 最后处理过的html内容
      var ret = t.contentParts.join('')
      // this.setData({text:ret})可用rich-text显示 <rich-text nodes="{{text}}"></rich-text>
      console.log(ret)
    }).catch(e => {
      console.log(e)
    })
  }
=====================================
// 调用
strHtml = '接口返回的html'
this.initContent(strHtml)
=====================================
//this.setData({text:ret})可用rich-text显示
<rich-text nodes="{{text}}"></rich-text>

若认为该回答有用,给回答者点个[ 有用 ],让答案帮助更多的人