Search code examples
svgvuejs2png

Convert SVG to PNG and download, vue 2


I'm looking for a clean way to convert a SVG to PNG and download, in Vue 2. What is the best approach ?


Solution

  • I finally managed to come up with this solution:

    save() {
          const a = document.querySelector("a");
          const triggerDownload = (imgURI: string) => {
            const evt = new MouseEvent("click", {
              view: window,
              bubbles: false,
              cancelable: true,
            });
    
            a?.setAttribute("download", "FileName.png");
            a?.setAttribute("href", imgURI);
            a?.setAttribute("target", "_blank");
    
            a?.dispatchEvent(evt);
          };
          const canvas = document.getElementById("canvas") as HTMLCanvasElement;
          const ctx = canvas.getContext("2d");
          data = new XMLSerializer().serializeToString(
            document.getElementById("svgId") as Node
          );
          const DOMURL = window.URL || window.webkitURL || window;
    
          const img = new Image();
          const svgBlob = new Blob([data], { type: "image/svg+xml;charset=utf-8" });
          const url = DOMURL.createObjectURL(svgBlob);
    
          img.onload = function () {
            ctx?.drawImage(img, 0, 0);
            DOMURL.revokeObjectURL(url);
    
            const imgURI = canvas
              .toDataURL("image/png")
              .replace("image/png", "image/octet-stream");
    
            triggerDownload(imgURI);
            ctx?.clearRect(0, 0, canvas.width, canvas.height);
          };
    
          img.src = url;
        },