html and Svg to Canvas javascript

html and Svg to Canvas javascript

本文关键字:Canvas javascript to Svg and html      更新时间:2023-09-26
<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 代码。我想将其转换为画布图像。

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

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

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

您需要使用

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

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

您的解决方案运行良好。由于我没有在我的应用程序中使用 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);
        }
}

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

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

SVG

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

您可以创建自己的 innerHTML,如以下 setSVG:在此处输入图像描述

实际上,您只需要注意两个步骤:创建SVG上下文标签和设置属性(使用上下文(

createElementNS 和 setAttributeNS 是您可能需要的两种方法!

常见的命名空间如下:

    svg:
  • http://www.w3.org/2000/svg

  • xhtml:
  • http://www.w3.org/1999/xhtml

  • xlink:
  • http://www.w3.org/1999/xlink

  • xml:http://www.w3.org/XML/1998/namespace

  • xmlns:
  • http://www.w3.org/2000/xmlns/