【发布时间】:2021-05-29 11:55:53
【问题描述】:
我正在开发这个应用程序,我需要从 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, 0, 0, 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 input 功能来添加upload from url 功能?
请注意,对于upload from url 功能,输入侦听器内部的内容将是相同的。所以可能我必须对imgObj 和img.src 做点什么。
【问题讨论】:
标签: javascript html jquery canvas html5-canvas