Using SVG bitmaps in WeChat applets

There are two ways to use SVG in WeChat applets:

  1. Import SVG images using <image>the tag:

    • Save the SVG image to the project directory, which can be a local file or a network file.
    • Use the tag to import the SVG image in the WXML file <image>, and set its srcattribute as the path of the SVG image. For example:
      <image src="/images/icon.svg"></image>
      
    • Note that the tags in the WeChat applet <image>do not fully support SVG, and some features may not be displayed or the effect may not meet expectations.
  2. Use to <canvas>draw SVG graphics:

    • Add a tag to the WXML file <canvas>for drawing SVG graphics. For example:
      <canvas id="myCanvas"></canvas>
      
    • In the page's JS file, use the wx.createCanvasContextcreated <canvas>context object, and use SVG.js or other SVG libraries to parse and draw SVG graphics. For example:
      const SVG = require('相对路径/svg.js');
      
      Page({
              
              
        onReady: function () {
              
              
          const ctx = wx.createCanvasContext('myCanvas');
          const svg = SVG(ctx);
      
          // 使用 SVG.js API 解析和绘制 SVG 图形
          const svgElement = svg.load('/images/icon.svg');
          svg.draw(svgElement);
        },
      });
      
    • Note that SVG.js is used here as the library for SVG parsing and drawing, and you can also choose other SVG libraries to achieve the same function.

Please choose the appropriate way to use SVG in WeChat Mini Programs according to your specific needs. At the same time, note that there may be some restrictions on the support of SVG in WeChat applets, and the support of SVG in different versions of WeChat clients may vary. It is recommended to conduct a compatibility test before development.

Guess you like

Origin blog.csdn.net/gao511147456/article/details/131625629