如何将 ImageData 写入 HTML5 canvas 上下文?

How do you write ImageData to an HTML5 canvas context?

我能够生成新的 ImageData 对象,但无法将其呈现到 canvas 上下文。出于某种原因,canvas 二维上下文不喜欢它创建的 ImageData 对象

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = 50;
var height = 50;


var ci = ctx.createImageData(width,height); // ImageData { width: ..., height: ..., data: Uint8ClampedArray(10000) }

// Draw on ci ImageData object...

ctx.drawImage(ci, 0, 0, width, height);

但是,这会引发错误:

TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, SVGImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap.

如何将 ImageData 对象写入 canvas?

要将 ImageData 对象写回 canvas,您必须使用 context.putImageData() method

var ci = ctx.createImageData(width,height);
ctx.putImageData(ci, 0, 0);