Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do `createImageData()` and `new ImageData()` differ?

I noticed that two JavaScript API members look very similar:

  • Function CanvasRenderingContext2D.createImageData(width, height)
  • Constructor new ImageData(width, height)

How should I correctly choose which one to use? Or are they essentially interchangeable?

At a glance, one difference is that the ImageData constructor is marked as "This is an experimental technology / Because this technology's specification has not stabilized...".

like image 846
Nayuki Avatar asked Dec 05 '25 07:12

Nayuki


1 Answers

If both APIs can accomplish what you want, you can use either one. If an API has a relevant feature or restriction, then you need to decide according to these facts.

Features of CanvasRenderingContext2D.createImageData():

  • An old stable API function, supported in all browsers and versions.
  • Needs an existing 2D context object in order to create an ImageData object.
  • Can use the form createImageData(imagedata) to clone an ImageData object.

Features of new ImageData():

  • An API function that is considered experimental. Not supported in any version of Microsoft Internet Explorer!
  • Is preferred when creating an ImageData in a worker thread. (Is ctx.createImageData() considered thread-unsafe?)
  • Is a freestanding constructor, not requiring a 2D context object first.
  • Can use the form new ImageData(array, width, height) to build an ImageData based on a pixel array.
like image 193
Nayuki Avatar answered Dec 07 '25 19:12

Nayuki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!