html 和 Svg 到 Canvas javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18271898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:15:04  来源:igfitidea点击:

html and Svg to Canvas javascript

javascripthtmlcanvassvghtml2canvas

提问by user2622044

<div id="Contents">
<div style="float:left;margin-left:10px;">
<svg></svg>
</div>
<div style="float:left;margin-left:10px;">
<svg></svg>
</div>
</div>

This is my html code. I want to convert it canvas image.

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

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

  }
});

I use html2canvas plugin for convert it to image but It does not show svg. I solve converting svg tp canvas but now html2canvas not working

我使用 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();
      }
    });

I can convert svg to canvas but html2canvas function not working.

我可以将 svg 转换为画布,但 html2canvas 功能不起作用。

回答by shinobi

You will need to use canvg library for drawing this svg to a temporary canvas and then remove that canvas once you take the screenshot using html2canvas.

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

Here is the link for canvg : https://github.com/canvg/canvg

这是 canvg 的链接:https: //github.com/canvg/canvg

Try this:

尝试这个:

//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');

回答by ABHILASH SB

As the html2canvas don't take svg elements, you need to convert all svg elements to canvas before you call the html2canvas method. You could use the canvglibrary to convert all the svg to canvas. You can pass the jquery object(which needs to convert from svg to canvas, can also be a parent element) to the following method:

由于 html2canvas 不带 svg 元素,因此您需要在调用 html2canvas 方法之前将所有 svg 元素转换为 canvas。您可以使用canvg库将所有 svg 转换为画布。您可以将 jquery 对象(需要从 svg 转换为 canvas,也可以是父元素)传递给以下方法:

function svgToCanvas (targetElem) {
var nodesToRecover = [];
var nodesToRemove = [];

var svgElem = targetElem.find('svg');

svgElem.each(function(index, node) {
    var parentNode = node.parentNode;
    var svg = parentNode.innerHTML;

    var canvas = document.createElement('canvas');

    canvg(canvas, svg);

    nodesToRecover.push({
        parent: parentNode,
        child: node
    });
    parentNode.removeChild(node);

    nodesToRemove.push({
        parent: parentNode,
        child: canvas
    });

    parentNode.appendChild(canvas);
});

html2canvas(targetElem, {
    onrendered: function(canvas) {
        var ctx = canvas.getContext('2d');
        ctx.webkitImageSmoothingEnabled = false;
        ctx.mozImageSmoothingEnabled = false;
        ctx.imageSmoothingEnabled = false;
    }
});

}

}

回答by SrinivasG

Your solution works beautifully. Since I am not using jQuery in my application, I had to change couple of lines in svgCanvas for getting the svg elements and iterating through them. The rest of the functions worked without any changes. My code is...

您的解决方案效果很好。由于我没有在我的应用程序中使用 jQuery,我不得不更改 svgCanvas 中的几行来获取 svg 元素并遍历它们。其余功能无需任何更改即可工作。我的代码是...

function svgToCanvas (targetElem) {
        var nodesToRecover = [];
        var nodesToRemove = [];

        var svgElems = document.getElementsByTagName("svg");

        for (var i=0; i<svgElems.length; i++) {
            var node = svgElems[i];
            var parentNode = node.parentNode;
            var svg = parentNode.innerHTML;

            var canvas = document.createElement('canvas');

            canvg(canvas, svg);

            nodesToRecover.push({
                parent: parentNode,
                child: node
            });
            parentNode.removeChild(node);

            nodesToRemove.push({
                parent: parentNode,
                child: canvas
            });

            parentNode.appendChild(canvas);
        }
}

回答by Alessandro Minoccheri

html2canvas doesn't allow to save SVG is an issue.
https://github.com/niklasvh/html2canvas/issues/95

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

If you want to save an SVG you an follow other way, like to transform your SVG into a PNG for example

如果你想保存一个 SVG 你可以按照其他方式,比如将你的 SVG 转换为 PNG

SVG -> canvas -> PNG -> canvas -> PNG

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

回答by u10749067

You can create your own innerHTML, like the following setSVGenter image description here

你可以创建你自己的innerHTML,像下面这样setSVG在此处输入图片描述

In fact, you only need to pay attention to two steps: creating the SVG context label and setting properties (with context)

其实只需要注意两步:创建SVG上下文标签和设置属性(带上下文)

createElementNS and setAttributeNS are two methods you may need!

createElementNS 和 setAttributeNS 是你可能需要的两个方法!

Common namespaces are as follows:

常见的命名空间如下: