How do you write ImageData to an HTML5 canvas context?

3.1k views Asked by At

I am able to generate a new ImageData object, but not able to render that to a canvas context. For some reason, the canvas 2d context does not like the ImageData objects it created.

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);

However, this throws an error:

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

How do you write an ImageData object to a canvas?

1

There are 1 answers

0
Xeoncross On BEST ANSWER

To write an ImageData object back to the canvas, you must use context.putImageData() method.

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