gpt4 book ai didi

javascript - html 和 Svg 到 Canvas javascript

转载 作者:技术小花猫 更新时间:2023-10-29 12:53:06 26 4
gpt4 key购买 nike

<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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com