【问题标题】:Can't download my svg to png无法将我的 svg 下载到 png
【发布时间】:2017-05-30 06:59:42
【问题描述】:

谁能告诉我为什么我的 svg to 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>

【问题讨论】:

    标签: javascript jquery canvas svg canvg


    【解决方案1】:

    你有一大堆问题:

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

    在我更正的代码中,我让画布 div 可见,因此您可以看到它在工作。不过,画布通常是 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>

    【讨论】:

    • 嘿罗伯特,谢谢你的回答,但是当你点击保存时如何将它保存到我的浏览器,你必须将它保存到我的浏览器你是怎么做到的
    • 嘿,罗伯特,我是 jquery 新手,您不能在我的代码中编辑解决方案
    • 再问一个问题,我已经更正了您提供的代码中的问题。请务必解释为什么我的其他评论中链接的答案不能解决您的问题。
    猜你喜欢
    • 2020-09-27
    • 1970-01-01
    • 2019-10-27
    • 2019-08-09
    • 2022-12-16
    • 2021-09-03
    • 2017-05-13
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多