如何解决如何将图像从 url 沿侧输入类型文件加载到 html5 画布?
我正在开发这个应用程序,我需要将图像从 url 和用户硬盘上传到 html5 画布。我已经为用户从硬盘驱动器的输入实现了该功能,但我不知道如何从 url 添加图像。
我以前从 input type file
加载的代码都在输入的事件侦听器中。它有很多功能,因为该应用程序还需要对图像进行 text
输入。所以 image from url
也应该具有相同的功能。
请注意,imgObj
位于事件侦听器内。我尝试将 img.src
更改为 url 以对其进行测试,但即使图像加载,我也无法再下载它。控制台抛出这个错误:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
at HTMLButtonElement.<anonymous>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const btnDownload = document.getElementById('btnDownload');
const fileUpload = document.getElementById('file-upload');
fileUpload.addEventListener('change',function(e) {
let imgObj = new Image();
imgObj.onload = draw;
imgObj.onerror = Failed;
imgObj.src = URL.createObjectURL(this.files[0]);
// imgObj.src = 'https://static.vecteezy.com/system/resources/previews/000/094/478/original/free-abstract-pattern-vector.jpg';
// some functions to write on image
});
function draw() {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
const nw = this.naturalWidth;
const nh = this.naturalHeight;
ctx.drawImage(this,nw,nh);
};
function Failed() {
console.error("The provided file Couldn't be loaded as an Image media");
};
btnDownload.addEventListener('click',() => {
const a = document.createElement('a');
document.body.appendChild(a);
a.href = canvas.toDataURL();
a.download = "canvas-image.png";
a.click();
document.body.removeChild(a);
});
<canvas id="canvas" width="800" height="500"></canvas>
<input type="file" id="file-upload" />
<button id="btnDownload">Download</button>
简而言之,如何通过保留 upload from url
功能来添加 upload from input
功能?
请注意,对于 upload from url
功能,输入侦听器中的内容将相同。所以可能我必须对 imgObj
和 img.src
做些什么。
解决方法
您遇到了 CORS 问题。 CORS 是一种协议,旨在防止网站从其他网站访问您的数据(跨域数据)。由于图像在 Web 早期就已经存在,由于向后兼容性问题,无法阻止跨源图像加载,但可以阻止访问此类数据。
因此,当您将跨域图像绘制到画布中时,画布会被“污染”,因此您无法再使用它做很多事情,包括将其内容检索为数据 URL。从文件系统上传的图片是安全的,因为用户必须选择加入。
所以为了使用图像数据,你必须告诉浏览器图像必须以跨域方式加载。您可以通过设置 crossOrigin
属性或属性来实现:
<img src="https://static.vecteezy.com/system/resources/previews/000/094/478/original/free-abstract-pattern-vector.jpg" crossorigin>
let imgObj = new Image();
imgObj.src =
"https://static.vecteezy.com/system/resources/previews/000/094/478/original/free-abstract-pattern-vector.jpg";
imgObj.crossOrigin = "";
使用此属性/属性,如果图像不支持 CORS,加载将失败,甚至不会显示。但如果是这样,就像在本例中一样,您将能够获取图像数据。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。