【问题标题】:How do I get an image from a blob url in JS?如何从 JS 中的 blob url 获取图像?
【发布时间】:2017-11-02 14:19:59
【问题描述】:

我在将图像从文件(图像)输入加载到画布时遇到问题。 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>

我的三个可见对象正在被绘制,但是当输入图像并单击加载按钮时,图像没有被绘制。

【问题讨论】:

  • window.onload = picEditor(); 这会执行picEditor() 并将返回值分配为onload 处理程序,因此这应该是window.onload = picEditor;
  • 谢谢,我试过 img.onload = function() {ctx.drawImage(...);} 而不是 ctx.drawImage(...);它奏效了。

标签: javascript html5-canvas


【解决方案1】:

您必须等到图像准备好才能在画布上绘制它

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

【讨论】:

  • 我收到 errorReporting: unhandledrejection: TypeError: 无法在“URL”上执行“createObjectURL”:重载解析失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 2020-03-16
相关资源
最近更新 更多