html和Svg到Canvas javascript

use*_*044 11 html javascript svg canvas html2canvas

<div id="Contents">
<div style="float:left;margin-left:10px;">
<svg></svg>
</div>
<div style="float:left;margin-left:10px;">
<svg></svg>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的HTML代码.我想转换它的画布图像.

html2canvas($("#Contents"), {
  onrendered: function(canvas) {
   window.open(canvas.toDataURL());

  }
});
Run Code Online (Sandbox Code Playgroud)

我使用html2canvas插件将其转换为图像,但它不显示svg.我解决了转换svg tp画布但现在html2canvas无法正常工作

  var $to=$("#MainContents").clone();

            $($to).children(".box").each(function() {
    var svg = ResizeArray[$(this).children(".box-content").children().attr("new-id")-1].svg();
            var Thiscanvas = document.createElement("canvas");
            Thiscanvas.setAttribute("style", "height:" + 100 + "px;width:" + 100+ "px;");

            canvg(Thiscanvas, svg);

            $(this).append(Thiscanvas);

        });
        html2canvas($($to), {
      onrendered: function(canvasq) {
        var w=window.open(canvasq.toDataURL());
        w.print();
      }
    });
Run Code Online (Sandbox Code Playgroud)

我可以将svg转换为canvas但html2canvas函数无效.

shi*_*obi 9

您将需要使用canvg库将此svg绘制到临时画布,然后在使用html2canvas截取屏幕截图后删除该画布.

以下是canvg的链接:https://github.com/canvg/canvg

试试这个:

//find all svg elements in $container
//$container is the jQuery object of the div that you need to convert to image. This div may contain highcharts along with other child divs, etc
var svgElements= $container.find('svg');

//replace all svgs with a temp canvas
svgElements.each(function () {
    var canvas, xml;

    canvas = document.createElement("canvas");
    canvas.className = "screenShotTempCanvas";
    //convert SVG into a XML string
    xml = (new XMLSerializer()).serializeToString(this);

    // Removing the name space as IE throws an error
    xml = xml.replace(/xmlns=\"http:\/\/www\.w3\.org\/2000\/svg\"/, '');

    //draw the SVG onto a canvas
    canvg(canvas, xml);
    $(canvas).insertAfter(this);
    //hide the SVG element
    this.className = "tempHide";
    $(this).hide();
});

//...
//HERE GOES YOUR CODE FOR HTML2CANVAS SCREENSHOT
//...

//After your image is generated revert the temporary changes
$container.find('.screenShotTempCanvas').remove();
$container.find('.tempHide').show().removeClass('tempHide');
Run Code Online (Sandbox Code Playgroud)


Ale*_*eri -1

html2canvas 不允许保存 SVG 是一个问题。
https://github.com/niklasvh/html2canvas/issues/95

如果您想保存 SVG,您可以采用其他方式,例如将 SVG 转换为 PNG

SVG -> 画布 -> PNG -> 画布 -> PNG