【问题标题】:onClick "save image as" in React在 React 中单击“将图像另存为”
【发布时间】:2020-06-10 03:06:55
【问题描述】:

我想在用户点击图片时模拟Save Image As

我阅读了thisthis 线程,但找不到答案。

我正在使用 CRA,但图像在我的服务器上不是。有什么方法可以实现吗?

这是一个沙盒:

https://codesandbox.io/s/save-image-as-react-pm3ts?file=/src/App.js


 <a
    href="https://img.mipon.org/wp-content/uploads/2019/12/14094031/logo-cover-website.png"
    download
      >
        <img
          download
          alt="Mipon"
          style={{ width: "300px" }}
          onClick={() => console.log("should trigger save image as")}
          src="https://img.mipon.org/wp-content/uploads/2019/12/14094031/logo-cover-website.png"
        />
</a>

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    下载属性将无法按预期工作,因为 Blink 引擎将阻止跨域 &lt;a download&gt;。结帐Deprecations and removals in Chrome 65

    为了避免本质上是用户介导的跨域信息 泄漏,Blink 现在会忽略下载属性的存在 在具有跨原点属性的锚元素上。请注意,这 适用于 HTMLAnchorElement.download 以及元素 自己。

    您可以尝试将图像绘制到画布元素并下载其 dataURL。但是这种方法只有在请求的域具有允许共享请求的Access-Control-Allow-Origin 标头时才有效。未经 CORS 批准的图像会污染画布,当您尝试使用 toDataURL() 之类的方法时,您将遇到错误 Tainted canvases may not be exported download image。在这种情况下,您可以使用 Cloudinary 之类的服务托管图像,然后使用画布下载方法即可。

    这是一个使用画布下载图像的函数,您可以在 onclick 事件处理程序中使用它:

    function downloadImage(src) {
      const img = new Image();
      img.crossOrigin = 'anonymous';  // This tells the browser to request cross-origin access when trying to download the image data.
      // ref: https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image#Implementing_the_save_feature
      img.src = src;
      img.onload = () => {
        // create Canvas
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        // create a tag
        const a = document.createElement('a');
        a.download = 'download.png';
        a.href = canvas.toDataURL('image/png');
        a.click();
      };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 2014-05-05
      • 2023-01-03
      • 2017-04-15
      • 1970-01-01
      相关资源
      最近更新 更多