SVG 이미지를 PNG로 변환해보자.

왼쪽은 SVG 이고 오른쪽은 PNG이다.

 

HTML 소스

PS. 다운받은 소스 주석 풀어서 사용한다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>svg2png</title>
</head>
<body>
  <svg width="80" height="120" viewBox="-1 -1 12 20" stroke-width=".25" stroke="#fff">
    <polygon points="1, 1  2, 0  8, 0  9, 1  8, 2  2, 2"/>
    <polygon points="9, 1 10, 2 10, 8  9, 9  8, 8  8, 2"/>
    <polygon points="9, 9 10,10 10,16  9,17  8,16  8,10"/>
    <polygon points="9,17  8,18  2,18  1,17  2,16  8,16"/>
    <polygon points="1,17  0,16  0,10  1, 9  2,10  2,16"/>
    <polygon points="1, 9  0, 8  0, 2  1, 1  2, 2  2, 8"/>
    <polygon points="1, 9  2, 8  8, 8  9, 9  8,10  2,10"/>
  </svg>
  <image id="img"></image>
  <script>
    const $svg = document.querySelector("svg");
    const data = new XMLSerializer().serializeToString($svg);
    const blob = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
    const $canvas = document.createElement("canvas");
    const {width, height} = $svg.getBoundingClientRect();
    $canvas.width = width;
    $canvas.height = height;
    const ctx = $canvas.getContext('2d');
    /* 다운로드 임시주석
    const img = new Image();
    img.onload = (e) => {
        ctx.drawImage(e.target, 0, 0);
        const $link = document.createElement("a");
        $link.download = "image.png";
        $link.href = $canvas.toDataURL("image/png");
        $link.click();
    };
    */
    img.src = URL.createObjectURL(blob);    
  </script>
</body>
</html>
728x90

+ Recent posts