您如何将ImageData写入HTML5画布上下文?

时间:2018-09-27 15:58:28

标签: javascript html5 html5-canvas imagedata

我能够生成一个新的ImageData对象,但是无法将其呈现到画布上下文。由于某些原因,canvas 2d上下文不喜欢它创建的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对象写入画布?

1 个答案:

答案 0 :(得分:0)

要将ImageData对象写回到画布,必须使用context.putImageData() method

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