【问题标题】:How to convert div#WareHouse with SVG inside to image如何将带有 SVG 的 div#WareHouse 转换为图像
【发布时间】:2019-10-10 11:39:15
【问题描述】:

如何将带有SVG的div#WareHouse转换为图像,然后下载并居中div#WareHouse。我想在点击提交后生成div#WareHouse作为图像代码:

<div id="WareHouse">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 48px; left: 8px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 76px; left: 56px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 104px; left: 104px;">
  <img width="80"
    src="http://rgrzymala.pl/2.svg" style="top: 132px; left: 152px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 160px; left: 200px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 188px; left: 248px;">
  <img width="80" src="http://rgrzymala.pl/2.svg"
    style="top: 216px; left: 296px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 244px; left: 344px;"><img width="80" src="http://rgrzymala.pl/2.svg" style="top: 272px; left: 392px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 300px; left: 440px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 328px; left: 488px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 356px; left: 536px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 384px; left: 584px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 412px; left: 632px;">
  <img width="80"
      src="http://rgrzymala.pl/2.svg" style="top: 440px; left: 680px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 468px; left: 728px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 496px; left: 776px;">
  <img width="80" src="http://rgrzymala.pl/2.svg"
      style="top: 524px; left: 824px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 552px; left: 872px;">
  <img width="80" src="http://rgrzymala.pl/2.svg" style="top: 580px; left: 920px;">  
</div>

我在 html2canvas 库中尝试过,但无济于事。显然,也许它不支持 SVG。这里是a link

【问题讨论】:

    标签: javascript jquery svg iframe html5-canvas


    【解决方案1】:

    我认为最好的方法是从一开始就使用画布。

    然后您可以使用 JS,因为您必须在画布上绘制图像(使用您的 SVG),如下所示:

    var img = new Image();
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
    }
    img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
    

    请注意,drawImage 接受图像以及 X 和 Y 坐标。有关更多信息,请参阅现有问题:Drawing an SVG file on a HTML5 canvas

    一旦您按照自己的喜好绘制了 SVG,就可以在画布上使用 .toDataURL()。像这样的:

    var canvas = document.getElementById('canvas');
    var dataURL = canvas.toDataURL();
    

    上面会返回一个base64编码的字符串,然后可以输出到浏览器提示保存。以下内容很好地概述了这一点:How To Save Canvas As An Image With canvas.toDataURL()?

    还有一个库可以帮助转换和保存:canvas2image

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 2012-09-17
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多