I have a function that uses html2canvas to download a few divs as images. I want to be able to also add a title at the top of the image when its saved, which would be the chartColumnID.
function saveAsImage(chartColumnID){
html2canvas($('#'+ chartColumnID),
{
onrendered: function (canvas) {
var a = document.createElement('a');
a.href = canvas.toDataURL("image/png");
a.download = chartColumnID;
a.click();
}
});
};
I've tried something like this but it doesnt work, no title appears. ive moved the a.text= to different lines to double check if i was maybe putting it in the wrong place but no luck.
function saveAsImage(chartColumnID){
html2canvas($('#'+ chartColumnID),
{
onrendered: function (canvas) {
var a = document.createElement('a');
a.href = canvas.toDataURL("image/png");
a.download = chartColumnID;
a.text= (15, 15, chartColumnID.replace(/([A-Z])/g, ' $1').trim());
a.click();
}
});
};
Does anyone have any idea of how to make the chart column id a title also?
You can try drawing a text on a canvas (I did not checked that):
function saveAsImage(chartColumnID) {
html2canvas($('#' + chartColumnID), {
onrendered: function(canvas) {
// ----------------------------- here we draw text:
const fontHeight = 14;
const text = String(chartColumnID);
const ctx = canvas.getContext("2d");
ctx.font = fontHeight + "px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "red"; // text color
ctx.fillText(text, 0, fontHeight);
// ------------------------------ your code as ususal:
var a = document.createElement('a');
a.href = canvas.toDataURL("image/png");
a.download = chartColumnID;
a.click();
}
});
};
Example of how it should look like on canvas:
var canvas = document.getElementById("c");
var chartColumnID = (Math.random() * 1000 + 1) | 0;
canvas.width = 100;
canvas.height = 100;
const fontHeight = 14;
const text = String(chartColumnID);
const ctx = canvas.getContext("2d");
ctx.font = fontHeight + "px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "red"; // text color
ctx.fillText(text, 0, fontHeight);
canvas { border: 1px solid }
<canvas id="c" />