Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 1x 8x 8x 8x 8x 8x 8x 2x 2x 8x 8x 2x 2x 2x 2x 2x 2x 8x 8x | import defined from "./defined.js";
const context2DsByWidthAndHeight = {};
/**
* Extract a pixel array from a loaded image. Draws the image
* into a canvas so it can read the pixels back.
*
* @function getImagePixels
*
* @param {HTMLImageElement|ImageBitmap} image The image to extract pixels from.
* @param {number} width The width of the image. If not defined, then image.width is assigned.
* @param {number} height The height of the image. If not defined, then image.height is assigned.
* @returns {ImageData} The pixels of the image.
*/
function getImagePixels(image, width, height) {
Eif (!defined(width)) {
width = image.width;
}
Eif (!defined(height)) {
height = image.height;
}
let context2DsByHeight = context2DsByWidthAndHeight[width];
if (!defined(context2DsByHeight)) {
context2DsByHeight = {};
context2DsByWidthAndHeight[width] = context2DsByHeight;
}
let context2d = context2DsByHeight[height];
if (!defined(context2d)) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
// Since we re-use contexts, use the willReadFrequently option – See https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-will-read-frequently
context2d = canvas.getContext("2d", { willReadFrequently: true });
context2d.globalCompositeOperation = "copy";
context2DsByHeight[height] = context2d;
}
context2d.drawImage(image, 0, 0, width, height);
return context2d.getImageData(0, 0, width, height).data;
}
export default getImagePixels;
|