Closed1

SVG to PNG on Canvas

黒ヰ樹黒ヰ樹

ツールにしたかったけどXSSになりそうだったので

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>SVG to PNG on Canvas</title>
    <meta name="description" content="Zenn" />
  </head>
  <body>
    <canvas id="myCanvas" width="480" height="480"></canvas>
    <script>
      const svgString =
        `<svg xmlns="http://www.w3.org/2000/svg" width="480" height="480" viewBox="0 0 32 32"><circle cx="16" cy="16" r="16" fill="red" /></svg>`;
      const svgBlob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
      const url = URL.createObjectURL(svgBlob);
      const img = new Image();
      img.onload = function () {
        const canvas = document.getElementById("myCanvas");
        const ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // ctx.fillStyle = "white"; // "black"
        // ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0);
        URL.revokeObjectURL(url);
      };
      img.crossOrigin = "anonymous";
      img.src = url;
    </script>
  </body>
</html>
このスクラップは15時間前にクローズされました