javascript - html 和 Svg 到 Canvas javascript

标签 javascript html canvas svg 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>

这是我的 html 代码。我想将其转换为 Canvas 图像。

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

  }
});

我使用 html2canvas 插件将其转换为图像,但它不显示 svg。 我解决了转换 svg tp canvas 但现在 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();
      }
    });

我可以将 svg 转换为 Canvas ,但 html2canvas 函数不起作用。

最佳答案

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

这是 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');

关于javascript - html 和 Svg 到 Canvas javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18271898/

相关文章:

javascript - 使用 Javascript、Canvas 和 Alpha 检测进行碰撞检测

JAVA - swing - 使用目标 Canvas 的反转/否定颜色进行绘制/填充

javascript - d3.js - 如何插入新的同级元素

javascript - 调用对象内的函数作为指令的参数

javascript - 如何修复vim中的JSON缩进?

jquery - 视频背景大小问题

javascript - Google Docs 如何在 JavaScript 中全屏显示

javascript - 在对象内部调用 JS 函数

javascript - 如何避免 Highcharts 中的水平滚动条

javascript - 无尽的控制台日志,javascript不会离开函数requestAnimationFrame