在画布上显示SVG字符串

我想在画布上显示一串SVG;

一种方法是在页面上有一个虚拟img元素,并用它将SVG“转换”为可以在画布上绘制的东西。

const svg='<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="1657" height="1235" viewBox="0 0 1657 1235">rn  <title>MTF</title>rn<rect x="10" y="10" width="100" height="100" stroke="blue" fill="purple" fill-opacity="0.5" stroke-opacity="0.8"/></svg>';
const svgURL = `data:image/svg+xml,${svg}`;

const img = document.getElementById('i');
img.setAttribute('src', svgURL);
const canvas = document.getElementById('c');
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
<div>
  <canvas id="c">
  </canvas>
</div>
<img src="" id="i"/>

你可以使用canvg。 它允许您将SVG文档直接渲染到画布上。

链接地址: http://www.djcxy.com/p/18327.html

上一篇: Display string of SVG on canvas

下一篇: Convert SVG SMIL attribute animation to CSS