使用html2canvas时未显示SVG

Ken*_*ura 3 svg html2canvas canvg

我正在一个项目中,我需要在客户端生成pdf文件(onclick saveFile as PDF),因为一些数据不会发送到服务器。我已经阅读了有关这些可用选项的信息;fileSaver.js和html2canvas似乎没有帮助。我也想指出,JavaScript并不是很好。这是我的js代码

<script type="text/javascript">
$(document).ready(function() {
    $("#saveOutput").click(function() {
        $("#Screenshot").html2canvas({ 
                onrendered: function(canvas) {
                var png = canvas.toDataURL()
                window.open(png);
              }
            });
          });
  });
Run Code Online (Sandbox Code Playgroud)

和我的HTML

 <div id="Screenshot">
<p>This is it</p>
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="250" height="250" style="height: 250px; width: 250px;">       
      <circle id="1" cx="100" cy="100" r="25" fill="#A52A2A"></circle>
  </svg>
</div>
<div id="content">
    <a class="button" id="saveOutput" href="#">Save as File</a>
</div>
Run Code Online (Sandbox Code Playgroud)

为什么无法显示SVG文件?这些文件如何转换为Canvas?有人可以向我展示代码示例吗?任何帮助将不胜感激

Isa*_*pes 27

就像其他答案中已经说过的那样:最新的 html2canvas 支持 svg 元素。

但显然 CSS 没有应用并且在设置 css“width”样式和 svg“width”属性时有一个错误。

在截图之前,我对 svg 元素添加了处理。

var svgElements = document.body.querySelectorAll('svg');
svgElements.forEach(function(item) {
    item.setAttribute("width", item.getBoundingClientRect().width);
    item.setAttribute("height", item.getBoundingClientRect().height);
    item.style.width = null;
    item.style.height= null;
});
Run Code Online (Sandbox Code Playgroud)

编辑:根据评论添加高度


Rag*_*i K 5

  • 解决方案1:您可以使用支持svg元素的最新html2canvas。
  • 解决方案2:在调用html2canvas函数之前,您可以将所有现有的svg元素转换为html2canvas支持的canvas元素。对于此转换,您可以使用canvg.js。

  • 我使用的是v1.0.0-alpha.12版本的最新版本,但是,即使是非常简单的图形,我仍然无法渲染SVG标签。 (3认同)
  • 好吧,我确实可以渲染 svg 但我只能在指定宽度时渲染 `svg` 标签。 (2认同)