I'm implementing client side download of some (High)charts that I have. What I'm doing now is getting the SVG source of the charts, creating a "canvas" element & drawing the SVG to said element, and then downloading the image using toBlob/Filesaver.js. See code below:
// draw the svg to a canvas
var c = document.createElement("canvas");
canvg(c, file);
// scrape the image from the canvas as png or jpg and download it in full quality
c.toBlob(function (blob) {
saveAs(blob, fileName);
}, contentType, 1);
Right now the download works fine as expected, but it seems that the canvas element I created, c
, has been attached to the window and sticks around even after the download finishes.
Calling c.remove()
doesn't help. c.parentNode
and c.parentElement
are null (obviously since I haven't attached c
to the DOM) so I can't call removeChild(c)
on anything.
I'm wondering how can I remove/delete element c
? Is c = undefined/null
good enough? Is there a more elegant way?
Once c
goes out of scope, it should get garbage collected automatically, so as long as canvg
doesn't keep an unnecessary reference to it.
To ensure c
eventually becomes not referenceable anymore, put the whole code in an IIFE:
(() => {
// draw the svg to a canvas
var c = document.createElement("canvas");
canvg(c, file);
// scrape the image from the canvas as png or jpg and download it in full quality
c.toBlob(function (blob) {
saveAs(blob, fileName);
}, contentType, 1);
})();
(otherwise, it'll stick around as window.c
)