简体   繁体   English

在画布上显示SVG字符串

[英]Display string of SVG on canvas

I want to display a string of SVG on a canvas; 我想在画布上显示一串SVG;

One method is to have a dummy img element on the page and use it to "transform" the SVG into something you can draw on a canvas. 一种方法是在页面上放置一个虚拟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\\">\\r\\n <title>MTF</title>\\r\\n<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"/> 

But this seems inefficient. 但这似乎效率很低。 How can I write the svg variable onto a canvas directly? 如何将svg变量直接写到画布上?

Alternatively, I could simply write it inside eg a div tag as it is valid code. 另外,我可以简单地将其写在例如div标签内,因为它是有效的代码。 However, I am using canvas to convert the SVG to png/jpg and save it to disk. 但是,我正在使用画布将SVG转换为png / jpg并将其保存到磁盘。 How can I accomplish this? 我该怎么做?

You could use canvg . 您可以使用canvg It allows you to render SVG documents directly onto a canvas. 它允许您将SVG文档直接呈现在画布上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM