reactjs - React 中的 onClick "save image as"

标签 reactjs

我想在用户单击图像时模拟图像另存为

我读到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>

最佳答案

下载属性将无法按预期工作,因为 Blink 引擎将阻止跨源 <a download> 。结账Deprecations and removals in Chrome 65 .

To avoid what is essentially a user-mediated cross-origin information leakage, Blink will now ignore the presence of the download attribute on anchor elements with cross origin attributes. Note that this applies to HTMLAnchorElement.download as well as to the element itself.

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

这是一个使用 Canvas 下载图像的函数,您可以在 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();
  };
}

Edit save-image-as-react

关于reactjs - React 中的 onClick "save image as",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62295172/

相关文章:

javascript - 如何修复index.tsx中的解析错误: Unexpected token,预期 ","?

css - 如何在ant-design组件中使用css-in-js?

reactjs - 在使用带有钩子(Hook)的导出类时,我应该远离类吗?

reactjs - typescript 给出类型 '"测试 "' is not assignable to type ' 未定义'

reactjs - 直接在material-ui的主题配置中支持渐变

reactjs - 过滤数据时 react 输入字段将失去焦点

node.js - 在 React/Node/Mongo/Mongoose 应用程序中使用日期的最佳解决方案

node.js - 如何设置 NODE_ENV?

javascript - 使用 redux 流下载文件

node.js - 没有得到 openAI model 的任何回应。给出错误 : Request failed with status code 429