Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

100*100的 canvas 占多少内存? #15

Open
xiaoyu2er opened this issue Nov 14, 2018 · 0 comments
Open

100*100的 canvas 占多少内存? #15

xiaoyu2er opened this issue Nov 14, 2018 · 0 comments

Comments

@xiaoyu2er
Copy link
Owner

题目

100*100的 canvas 占多少内存?

三年前端,面试思考 中提到了一个题目,非常有新意,这里分享一下当时面试的思考过程。

解题思路

其实真正的答案是多少我并不清楚,面试过程中面试官也不期待一个准确的答案,而是看你的思考过程。

如果了解过 Canvas 且做过滤镜相关的工作,可能调用过 imageData = ctx.getImageData(sx, sy, sw, sh); 这个 API。我记得这个 API 返回的是一个 ImageData 数组,包含了 sx, sy, sw, sh 表示的矩形的像素数据。

而且这个数组是 Uint8 类型的,且四位表示一个像素。

我在面试的时候只能想起来这些信息。猜想一下,我们在定义颜色的时候就是使用 rgba(r,g,b,a) 四个维度来表示,而且每个像素值就是用十六位 00-ff 表示,即每个维度的范围是 0~255,即 2^8 位,即 1 byte, 也就是 Uint8 能表示的范围。

所以 100 * 100 canvas 占的内存是 100 * 100 * 4 bytes = 40,000 bytes。

声明

这里的答案并不一定准确。

关于 alpha 的争论

有同学指出,alpha 不是 0-100 么?我起初也有这样的疑问,不过这篇文章中 https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas

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.

也就是说即便是 alpha 也是 0-255

那么如何表示 alpha 呢?

接下来这段代码中

可以看出,只需要用 0-255 表示 0-100 就可以啦~

参考资料

CanvasRenderingContext2D.getImageData() 返回一个ImageData对象,用来描述canvas区域隐含的像素数据,这个区域通过矩形表示,起始点为(sx, sy)、宽为sw、高为sh。

Uint8ClampedArray 描述了一个一维数组,包含以 RGBA 顺序的数据,数据使用 0 至 255(包含)的整数表示。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant