我想在用户单击图像时模拟图像另存为
。
我正在使用 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();
};
}
关于reactjs - React 中的 onClick "save image as",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62295172/