JS如何从Blob URL获取图像?

4

我在从文件(image input)中加载图像到画布(canvas)上遇到了问题。fileInput对象是图像选择器。这是站点上的一个JS文件。

<script>
function picEditor() {
    var fileInput = document.createElement("input");
    fileInput.setAttribute("type", "file");
    fileInput.setAttribute("accept", "image/png");
    fileInput.setAttribute("id", "fluff");
    document.body.appendChild(fileInput);

第二部分,创建图像。首先创建图像和加载按钮。按钮的单击函数应该将图像的源设置为文件输入的blob URL,然后在画布上绘制图像。

    var img = document.createElement("img");
    var loadButton = document.createElement("button");
    loadButton.onclick = function() {
        img.src = window.URL.createObjectURL(fileInput.files[0]);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    };
    loadButton.innerHTML = "Click here";
    document.body.appendChild(loadButton);

第三部分,创建了画布和渲染上下文。
    var canvas = document.createElement("canvas");
    canvas.style.position = "absolute";
    canvas.style.left = "740px";
    canvas.style.top = "15px";
    canvas.style.border = "1px #fa0 solid";
    canvas.width = 600;
    canvas.height = 600;
    document.body.appendChild(canvas);
    var ctx = canvas.getContext("2d");
}
window.onload = picEditor();
</script>

我的三个可见对象被绘制出来了,但是当输入了图片并且点击了"load"按钮时,图片没有被绘制出来。


1
window.onload = picEditor(); This executes picEditor() and assigns the return value as the onload handler, hence this should probably be window.onload = picEditor; - Andreas
谢谢,我尝试了img.onload = function() {ctx.drawImage(...);}而不是ctx.drawImage(...);,它起作用了。 - Benjamin Belisle
1个回答

1

在绘制画布上的图像之前,您必须等待图像准备就绪

loadButton.onclick = function() {
    img.onload = function() {
        ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
    };
    img.src = window.URL.createObjectURL(fileInput.files[0]);
};

我收到了错误报告:unhandledrejection: TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed. - YTG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接