无法将我的 svg 下载为 png

Can't download my svg to png

谁能告诉我为什么我的 svg 转 png 不能下载?我究竟做错了什么?我似乎找不到关于如何将我的 svg 下载到 png 的解决方案。是我的库还是我的代码?

function save(){
    $("#editor_save").click(function() {
        // the canvg call that takes the svg xml and converts it to a canvas
        canvg('canvas', $("#editor").html());

        // the canvas calls to output a png
        var canvas = document.getElementById("canvas");
        var img = canvas.toDataURL("image/png");
        // do what you want with the base64, write to screen, post to server, etc...
    });
}
<script src="canvg-master/canvg.js"></script>
<div id="editor" class="chart">
    <svg width="100" height="100">
        <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="red" />
    </svg><br />
    <button id="editor_save" onclick="save">Save</button>
</div>

你有一大堆问题:

  • canvg 顾名思义适用于 canvas,您甚至可以在从 this answer 复制的代码中调用 getElementById("canvas"),但尽管如此您没有实际上在你的问题标记中有一个 canvas 元素
  • 您正在使用 .html() 从 div 获取数据,但是 div 不仅包含 svg,它还有一个 <br /> 和按钮
  • 您已将复制的代码包装在保存函数中,但保存函数并未从任何地方调用
  • 您没有正确地包含正确的 canvas 脚本
  • 您没有包含 jQuery 但您正在使用该库

在我更正的代码中,我保留了 canvas div 可见,因此您可以看到它在工作。虽然 Te canvas 通常是 display:none,但您需要对 img 对象做其他事情。

$("#editor_save").click(function() {

// the canvg call that takes the svg xml and converts it to a canvas
  canvg('canvas', $("#svg")[0].outerHTML);

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
// do what you want with the base64, write to screen, post to server, etc...
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://canvg.github.io/canvg/rgbcolor.js"></script>
<script src="http://canvg.github.io/canvg/StackBlur.js"></script>
<script src="http://canvg.github.io/canvg/canvg.js"></script>
<div id="editor" class="chart">
<svg id="svg" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="red" />
</svg>
<br />
<button id="editor_save">Save</button>
</div>
<div>
  <canvas id="canvas" width="1000px" height="600px"></canvas> 
</div>