1👍
In order to get a higher resolution snapshot of the chart, you first need to resize it and then wait for it to redraw.
The simplest way to do that is to resize the parent and wait ~ 300ms
.
Note: if your chart is more complex (has significantly more data to draw), the resize & redraw might take longer, feel free to increase the timeout interval accordingly – it’s 321ms
now.
Because you need to wait for the chart to resize, you can’t use the initial click anymore. You need to trigger another one, after the chart has resized.
Lastly, I’m deleting the href
value after the download. If I don’t, any subsequent click on the button will return the first snapshot and, in case the chart is dynamic and you want to be able to snapshot it again without having to refresh the page.
Here’s how the code looks like:
function downloadImage(name, id) {
setTimeout(() => {
const a = $(id)[0];
a.href = $(name)[0].toDataURL("image/jpg");
a.click();
}, 321)
}
$('.download').on('click', function(e) {
const name = '#' + $(this).data('name');
const id = '#' + this.id;
const parent = $(name).parent();
if (!$(this).attr('href')) {
parent.css({ width: Math.max(1200, parent.width()) });
downloadImage(name, id);
e.preventDefault();
} else {
parent.css({ width: '' });
setTimeout(() => $(id).attr('href', ''));
}
});
Feel free to change 1200
to whatever min-width
you want for your chart. Currently, if the displayed chart width is larger than that value, you’ll download a bigger image, as you said in comments. I personally find that a bit weird.
If you change your mind, and want the downloaded chart to always have the same size (even when downloaded from larger monitors), replace
parent.css({ width: Math.max(1200, parent.width()) });
with
parent.css({ width: 1920 }); // or whatever fixed chart width you want
See it working: http://jsfiddle.net/websiter/Lzdc3bw1/
0👍
Custom dimensions can be applied by creating a new canvas
element along with a new canvas context
function downloadpng(chartname, chartid) {
var canvas = document.getElementById(chartname);
var url_base64jp = canvas.toDataURL("image/jpg");
var a = document.getElementById(chartid);
var resizedCanvas = document.createElement("canvas");
var resizedContext = resizedCanvas.getContext("2d");
resizedCanvas.height = "1080";
resizedCanvas.width = "1920";
resizedContext.drawImage(canvas, 0, 0, 1920, 1080);
url_base64jp = resizedCanvas.toDataURL("image/jpg");
a.href = url_base64jp;
}