微信小程序加载svg数据图片

微信小程序加载svg数据图片

  • 解决方案和步骤
    • 1. 获取svg数据
    • 2. 对数据进行转码
    • 3. 在wxml中使用

微信小程序如何加载动态的svg数据图片?

尝试过多种方式都不可行:

  1. 在使用
  2. 在src以base64方式使用

解决方案和步骤

通过远程服务获取svg图片数据,使用小程序背景渲染方式进行展现。

1. 获取svg数据

http.get(`/admin/base/open/captcha?height=50&width=100&color=#000`).then(res=>{
      const bg = toSvgCssDackground(res.data.data);
      this.setData({
        captchaId: res.data.captchaId,
        svgDataBG: bg
      })
    })
/* res.data.data数据示例 */
res.data.data = ""

2. 对数据进行转码

/**
 * 转换成svg的css背景字串
 * @param svgString 
 */
export const toSvgCssDackground = (svgString: string) => {
  let res = svgString;
  res = svgString
    .replace(', (~svgString.indexOf('xmlns') ? ' : '))

    //
    //   Encode (may need a few extra replacements)
    //
    .replace(/"/g, '\'')
    .replace(/%/g, '%25')
    .replace(/#/g, '%23')
    .replace(/{/g, '%7B')
    .replace(/}/g, '%7D')
    .replace(/</g, '%3C')
    .replace(/>/g, '%3E')

    .replace(/\s+/g, ' ');
  return `background-image: url("data:image/svg+xml,${res}")`;
}

3. 在wxml中使用

<image class="svg-captcha" style="{{svgDataBG}}" width="100" height="60">image>
.svg-captcha{
  width: 100px;
  height: 50px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

你可能感兴趣的:(小程序,微信小程序,小程序,svg)