【发布时间】: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