今天快速整理一下,如何讓 svg 的檔 用js轉成 PNG檔
這個方法區要 svg的整個 element來進行轉換,轉換後會自動下載
const svgToPNG = (svgElement) => { let svgData = new XMLSerializer().serializeToString(svgElement); //將svg資料序列話成 string let canvas = document.createElement( "canvas" ); //會了 把svg轉成png的 canvas let ctx = canvas.getContext( "2d" ); let img = new Image(); // (btoa 把 string to base64) img.setAttribute( "src", "data:image/svg+xml;base64," + btoa( svgData ) ); img.onload = function() { canvas.width = img.width; canvas.height = img.height; ctx.drawImage( img, 0, 0 ); let a = document.createElement("a"); a.download = "QRcode.png"; a.href = canvas.toDataURL( "image/png" ); a.click(); } };
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記