简体   繁体   English

html 和 Svg 到 Canvas javascript

[英]html and Svg to Canvas javascript

<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.这是我的 html 代码。 I want to convert it canvas image.我想将其转换为画布图像。

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

  }
});

I use html2canvas plugin for convert it to image but It does not show svg.我使用 html2canvas 插件将其转换为图像,但它不显示 svg。 I solve converting svg tp canvas but now html2canvas not working我解决了转换 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 功能不起作用。

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

As the html2canvas don't take svg elements, you need to convert all svg elements to canvas before you call the html2canvas method.由于 html2canvas 不带 svg 元素,因此您需要在调用 html2canvas 方法之前将所有 svg 元素转换为 canvas。 You could use the canvg library to convert all the svg to canvas.您可以使用canvg库将所有 svg 转换为画布。 You can pass the jquery object(which needs to convert from svg to canvas, can also be a parent element) to the following method:您可以将 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;
    }
    });
}

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.由于我没有在我的应用程序中使用 jQuery,我不得不更改 svgCanvas 中的几行来获取 svg 元素并遍历它们。 The rest of the functions worked without any changes.其余功能无需任何更改即可工作。 My code is...我的代码是...

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);
        }
}

html2canvas doesn't allow to save SVG is an issue. html2canvas 不允许保存 SVG 是一个问题。
https://github.com/niklasvh/html2canvas/issues/95 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

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:常见的命名空间如下:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM