I have an existing application that uses html canvas to generate a graph. There is a legend that also needs to be saved when the graph is saved. Currenlty, if I right click to save the image, only the graph is saved.
I came across Cavas2Image.js & html2canvas.js and have implemented both in my project.
I have wired up a button to save the image. Currently, when clicked it created a download file, but it is just called download and there is no extension. If I add extension .png it then works correctly. I do not know why this is not done by Cavas2Image, which is the whole point of using that library. I put breakpoints and it is hitting the method to add the .png extension.
Based on the documentation (or lack thereof) of canvas2image.js, I should be able to use the single method to save my canvas:
Canvas2Image.saveAsImage(canvas, null, null, "png");
Here is my full code block:
<div class="row">
<div class="col-md-12">
<div id="widget" class="canvas__container">
<canvas id="lineChartCanvas" class="chart chart-line canvas__canvas" chart-data="data" chart-labels="labels" style="height: 300px; width: 95%;"
chart-legend="true" chart-series="series" chart-click="onClick"></canvas>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<input type="button" class="btn btn-primary" id="btnSave" value="EXPORT CHART" />
</div>
</div>
<script>
$(function () {
$("#btnSave").click(function () {
html2canvas($("#widget"), {
onrendered: function (canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
//Canvas2Image.saveAsPNG(canvas);
Canvas2Image.saveAsImage(canvas, null, null, "png");
}
});
});
});
</script>
I am using the two javascript files listed above even though they are not shown here.