简体   繁体   English

在 React js 中将 svg 下载为 png

[英]Download svg as png in react js

I tried to download the svg tag element, actually the image that the svg renders using the next function:我尝试下载 svg 标签元素,实际上是 svg 使用下一个函数呈现的图像:

 // Get the SVG element
    const svg = document.getElementsByTagName('svg')[0];

    const canvas = document.createElement('canvas');
    canvas.width = svg.clientWidth;
    canvas.height = svg.clientHeight;

    const img = new Image();
    img.src = `data:image/svg+xml;utf8,${new XMLSerializer().serializeToString(
      svg,
    )}`;

    img.onload = function() {
      console.log(img)
      canvas.getContext('2d')?.drawImage(img, 0, 0);
    };

    const a = document.createElement('a');
    a.download = 'my-image.png';
    a.href = canvas.toDataURL();
    a.click();

When i click on the dowsnload buttoon, the image is downloaded but it is black without any character.当我点击 dowsnload 按钮时,图像被下载,但它是黑色的,没有任何字符。
Why it is hapening and how to get a valid image?为什么它会变黑以及如何获得有效图像?
PS: i investigated a lot of answer on the site but they don;t help. PS:我在网站上调查了很多答案,但他们没有帮助。 If someone will help with my example it will help me a lot.如果有人会帮助我的例子,那将对我有很大帮助。

The error occurs because you bring in an asynchronous context and don't wait for that and directly downloading the image.发生错误是因为您引入了异步上下文并且不等待它直接下载图像。

You can avoid it by moving the "download part" (see example 1) into the onload function or by packing away the onload and hoping that it will load fast enough (example 2).您可以通过将“下载部分”(参见示例 1)移动到onload函数中或通过打包onload并希望它加载得足够快(示例 2)来避免它。

Example 1:示例 1:

//...
    img.onload = function() {
      console.log(img)
      canvas.getContext('2d')?.drawImage(img, 0, 0);
      const a = document.createElement('a');
      a.download = 'my-image.png';
      a.href = canvas.toDataURL();
      a.click();
    };

Example 2:示例 2:

//...
canvas.getContext('2d')?.drawImage(img, 0, 0);
const a = document.createElement('a');
a.download = 'my-image.png';
a.href = canvas.toDataURL();
a.click();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM