我的应用程序中有一个d3图表,我想要的是截取图表的截图。我使用html2canvas.js和canvg.js插件将div内容转换为base64字符串。我使用内联样式绘制图表。我从另一篇文章中得到了这个解决方案。
我的图表中有矩形,我使用渐变色来填充矩形,但是当我拍摄截图时,不会显示矩形的背景颜色,请参见下面的图片↓↓。在搜索了一些解决方案之后,我了解到html2canvas插件有一些限制,并且canvg也会遇到一些设计问题。
var sContainer = $("#idtrendChartMain")
svgElements = $(sContainer).find('svg');
var savedSlideName;
//replace all svgs with a temp canvas
svgElements.each(function () {
var canvas, xml;
// canvg doesn't cope very well with em font sizes so find the calculated size in pixels and replace it in the element.
$.each($(this).find('[style*=em]'), function (index, el) {
$(this).css('font-size', getStyle(el, 'font-size'));
});
canvas = document.createElement("canvas");
sContainer[0].appendChild(canvas);
//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\"/, '');
//console.log(xml);
//xml = xml.replace(/xmlns:xlink=\"http:\/\/www\.w3\.org\/1999\/xlink\"/, '');
xml = xml.replace(/xlink:/g, '');
//draw the SVG onto a canvas
canvg(canvas, xml);
$(canvas).insertAfter(this);
//hide the SVG element
$(this).attr('class', 'tempHide');
$(this).hide();
});
html2canvas($(sContainer), {
allowTaint: true,
letterRendering: true,
onrendered: function (canvas) {
var base64 = canvas.toDataURL();
base64 = base64.replace('data:image/png;base64,', '');
//creating the request
var request = {};
request.Base64 = base64;
$.ajax({
type: "POST",
url: AQ.Verizon.Url + "/Home/StoreImage",
//async: false,
data: JSON.stringify({ request: request }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
},
error: function (e) {
alert("fail");
}
});
$(sContainer).find('canvas').remove();
$('svg').show();
}
});
我可以用我所拥有的解决这个问题,或者是用于截取屏幕截图的更好的插件。因为如果我使用波纹管代码,我将无法获得屏幕的精确截图,而且清晰度也很差。