Images

getImageFromCanvas

const getImageFromCanvas = (selector) => { let srcCanvas = document.querySelector(selector); //create a dummy CANVAS let destinationCanvas = document.createElement('canvas'); destinationCanvas.width = srcCanvas.width; destinationCanvas.height = srcCanvas.height; let destCtx = destinationCanvas.getContext('2d'); //create a rectangle with the desired color destCtx.fillStyle = '#FFFFFF'; destCtx.fillRect(0, 0, srcCanvas.width, srcCanvas.height); //draw the original canvas onto the destination canvas destCtx.drawImage(srcCanvas, 0, 0); //finally use the destinationCanvas.toDataURL() method to get the desired output; return destinationCanvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); // Convert image to 'octet-stream' to make it downloadable }

downloadFile

const downloadFile = (file, name) => { let link = document.createElement('a'); link.href = file; link.download = name; link.click(); }

Example usage:

document.querySelector('#chart-download-button').addEventListener('click', (event) => { const image = getImageFromCanvas('#chart-wrapper'); downloadFile(image, 'chart.png'); });