将 SVG 转换为 PNG/JPEG 不适用于 FF

时间:2021-03-09 15:23:33

标签: reactjs image svg firefox

我的脚本有问题,它在 dom 中找到一个 svg 并将 svg 下载为 jpeg 或 png。在 chrome 上一切正常,但在 Firefox 上我下载了一个空图像。你能帮我吗?

这是我的剧本

   const downloadImage = () =>{
    // Find the svg by ref
    const selectedSvg = chartRef.current
    const svgSizes = selectedSvg.getBBox()
    const width = svgSizes.width * scale
    const height = svgSizes.height * scale
    // Create a Blob of the svg
    const clonedSvgElement = selectedSvg.cloneNode(true);
    const xml = new XMLSerializer().serializeToString(clonedSvgElement);
    const blob = new Blob([xml],{type:'image/svg+xml;charset=utf-8'});
    const URL = window.URL || window.webkitURL || window;
    const blobURL = URL.createObjectURL(blob);
    // Create a canvas for drawing the new img
    const canvas = document.createElement('canvas');
    const context = canvas.getContext("2d");
    debugger;
    
   
    const image = new Image();
    // Add the img into the canvas and download it
    image.onload = () => { 
      canvas.width = width
      canvas.height = height    
      context.fillStyle = backgroundColor ?? "transparent";
      context.fillRect(0, 0, width, height);
      context.drawImage(image, 0, 0, width, height);
    
      const imgUri = canvas.toDataURL(type, compression);
      const link = document.createElement('a');
      link.download = fileName;
      link.href = imgUri;
      link.click();
    };

    image.src = blobURL;

  }

0 个答案:

没有答案
相关问题