HTML和Svg到画布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>
这是我的html代码。
$ b
This is my html code. I want to convert it canvas image.
html2canvas($("#Contents"), {
onrendered: function(canvas) {
window.open(canvas.toDataURL());
}
});
我使用html2canvas插件将其转换为图片,但不显示svg。
解决转换svg tp画布,但现在html2canvas不能正常工作
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
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函数无法正常工作。
I can convert svg to canvas but html2canvas function not working.
推荐答案
您需要使用canvg库将此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的链接: https://github.com/canvg/ canvg
Here is the link for 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');
这篇关于HTML和Svg到画布javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!