Originally from my Github blog

The title

How much memory does a 100*100 Canvas have?

At the end of three years, a topic was mentioned in the interview thinking, very innovative, here to share the interview thinking process at that time.

Their thinking

I don’t know what the real answer is, and the interviewer doesn’t expect an exact answer during the interview, it depends on your thinking process.

ImageData = ctx.getimageData (sx, sy, sw, sh); This API. As I recall, the API returns an ImageData array containing the pixel data for the sX, SY, SW, sh rectangles.

And the array is of the Uint8 type and four bits represent one pixel.

That’s all I could think of during the interview. Suppose we define the color in four dimensions rGBA (r,g,b,a), and each pixel value is expressed in 16-bit 00-FF, which means the range of each dimension is 0~255, which is 2^8 bits, which is 1 byte, which is the range of Uint8.

So the memory footprint of 100 * 100 Canvas is 100 * 100 * 4 bytes = 40,000 bytes.

The statement

The answer here is not necessarily accurate.

The alpha debate

Somebody pointed out that alpha is not 0-100? I had the same question at first, but in this article developer.mozilla.org/en-US/docs/… said

The data property returns a Uint8ClampedArray which can be accessed to look at the raw pixel data; each pixel is represented by four one-byte values (red, green, blue, and alpha, in that order; that is, “RGBA” format). Each color component is represented by an integer between 0 and 255.

That means even alpha is 0-255

So how do you represent alpha?

In this next piece of code

As you can see, you only need to use 0-255 to represent 0-100

The resources

CanvasRenderingContext2D. GetImageData () returns a ImageData object, used to describe the canvas area implied pixel data, this area through the rectangles represent, the starting point for sw for (sx, sy), wide, high for sh.

Uint8ClampedArray describes a one-dimensional array of data in RGBA order represented as integers from 0 to 255 (included).

  • Developer.mozilla.org/zh-CN/docs/…
  • Developer.mozilla.org/zh-CN/docs/…
  • Developer.mozilla.org/en-US/docs/…

hiring

Ant Financial – Micro loan business group recruitment front can send your resume to [email protected] email subject: resume – Name – front attach your resume