【问题标题】:Javascript Canvas get data from image and display itJavascript Canvas 从图像中获取数据并显示它
【发布时间】:2019-06-08 16:59:25
【问题描述】:

我不知道为什么这不起作用。图像的 src 属性随着新数据的变化而改变,但图像实际上是不可见的。我尝试了几个不同的图像。它只是浏览器中的 javascript,需要 Jquery。

<body>
<img src="" id="test">
</body>
<script>
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    img.onload = getIt
    img.src = 'download.png';

    function getIt() {      
        canvas.width = this.width;
        canvas.height = this.height;
        const imageData = ctx.getImageData(0, 0, this.width, this.height);
        ctx.drawImage(this, canvas.width , canvas.height);
        ctx.putImageData(imageData, canvas.width, canvas.height);

        $('#test').get(0).src = canvas.toDataURL("image/png");
    }

</script>

我尝试了几个不同的图像,都是 png。目前这是该项目的全部代码,所以我预计不会有任何干扰。

结果是这样但是看不到图片:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAeCAYAAAAhDE4sAAAAMklEQVRIS+3SsQ0A....etc" id="test">

编辑:似乎它可能错误地从图像中获取数据,但我不知道为什么......我的意思是为什么它会获取数据但不完整或不正确?

【问题讨论】:

  • 我想问题是 getIt 永远不会被调用,因为它被设置为空图像上的事件处理程序,因此永远不会调用 onload。请您提供更多详细信息,说明您想通过此代码实现什么?
  • @Mikulas 必须调用 getIt 函数,否则 src 属性将不会使用图像数据进行更新。标题中解释了我想要实现的目标,即使用画布直接从图像数据中显示图像。
  • 两个问题,你是从http://something 还是file:///something 运行代码?如果您使画布在 html 页面上可见,图像是否存在?
  • 我同意 getit 正在运行,透明画布将 toDataURL 生成透明图像。提示图像在超时后无法加载并带有错误代码?
  • 另请注意,默认画布宽度由 css 或 html 中的 canvas 元素设置,我不确定 document.createElement("canvas") 的默认宽度是多少? this.width 可能是未定义的。

标签: javascript canvas imagedata


【解决方案1】:

请试试这个: (您不需要获取或放置图像数据)

你也在这样做:ctx.putImageData(imageData, canvas.width, canvas.height);。这意味着您正在完全在画布之外绘制图像。改为这样做:ctx.putImageData(imageData, 0,0);

const canvas = document.createElement("canvas");

    const ctx = canvas.getContext("2d");
    let img = new Image();
    img.onload = getIt
    img.src = "download.png";

    function getIt() {    
        canvas.width = this.width;
        canvas.height = this.height;
        //draw the image onto the canvas
        ctx.drawImage(this, 0,0);
        //use the data uri 
        test.src = canvas.toDataURL("image/png");
    }
<img src="" id="test">

【讨论】:

  • 啊哈!是的,解决了它,我认为 putimagedata 很重要,因为我们毕竟需要 dataurl,但始终 drawimage 更重要。虽然我不太了解 test.src ......它似乎是一个未定义的变量?它会自动引用具有相同名称或什么标签的图像?
  • 元素 ID 成为窗口的属性。但如果你愿意,你可以改用dicument,getElementById("test")
猜你喜欢
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多