How to export a canvas to an SVG file using Javascript

本文介绍如何使用JavaScript将Canvas内容转换为SVG字符串并下载为SVG文件,包括使用`<foreignObject>`嵌入Canvas内容,处理跨域限制以及推荐使用如fabric.js或canvg等库作为备选方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

To export a canvas to an SVG file using JavaScript, you can convert the canvas content to an SVG string and then save it as a file. Here’s an example:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <canvas id="my-canvas" width="200" height="200"></canvas>

  <button onclick="exportCanvasToSVG()">Export to SVG</button>

  <script>
    function exportCanvasToSVG() {
      const canvas = document.getElementById('my-canvas');
      const ctx = canvas.getContext('2d');

      const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="${canvas.width}" height="${canvas.height}">
        <foreignObject width="100%" height="100%">
          <div xmlns="http://www.w3.org/1999/xhtml">
            <style>
              /* Add your canvas styles here */
              canvas {
                background-color: white;
              }
            </style>
            ${canvas.outerHTML}
          </div>
        </foreignObject>
      </svg>`;

      const blob = new Blob([svgString], { type: 'image/svg+xml' });
      const url = URL.createObjectURL(blob);

      const link = document.createElement('a');
      link.href = url;
      link.download = 'canvas.svg';
      link.click();

      URL.revokeObjectURL(url);
    }
  </script>
</body>
</html>

In the above example, we have a canvas element with an id of my-canvas and a button with an onclick event that triggers the exportCanvasToSVG() function.

Inside the function, we select the canvas element using document.getElementById() and get its 2D rendering context using getContext('2d').

We then create an SVG string that wraps the canvas content using the <svg> and <foreignObject> elements. The canvas content is embedded within a <div> element inside the <foreignObject>. You can add custom styles to the <style> element within the <div> to customize the appearance of the canvas in the exported SVG.

Next, we create a Blob object with the SVG string and specify the MIME type as 'image/svg+xml'. We then create a URL for the blob using URL.createObjectURL().

After that, we create a <a> element dynamically using document.createElement(). We set the href attribute to the URL of the blob, the download attribute to the desired filename for the exported SVG file, and trigger a click event on the link using link.click().

Finally, we revoke the URL using URL.revokeObjectURL() to release the resources associated with the URL.

When the user clicks the “Export to SVG” button, the canvas content will be converted to an SVG file and downloaded with the specified filename.

Note that this method may have limitations due to cross-origin restrictions. If the canvas content is loaded from a different domain, you may encounter security errors. In such cases, you may need to use a server-side solution or a library that supports canvas to SVG conversion, such as fabric.js or canvg.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值