I have a d3 chart in my application and what I want is to take a screenshot of the chart. I am using html2canvas.js and canvg.js plugin to convert the div content to base64 string. I used inline styles for plotting the chart. I got this solution from another post.
I have rectangles in my chart and I used gradient color to fill the rectangles but when I take a screenshot the background color of rectangles are not be displayed, see images below ↓↓. After searching some solutions I understand the html2canvas plugin has some limitations and canvg will also have problems with some designs.
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();
}
});
Can I solve this problem with what I have got or is any a better plugin for taking the screenshot. Because if I use bellow code I will not get exact screenshot of the screen and also the clarity is poor.