All files bitmap.mjs

29.62% Statements 8/27
60% Branches 6/10
40% Functions 2/5
29.62% Lines 8/27

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75                                                                                                      37x 37x 37x                     25x     25x     25x 25x 25x    
 
/**
 * 
 * @param {ImageBitmap} bitmap
 * @returns {ImageData}
 */
export function getBitmapFromImageSource(bitmap) {
    const canvas = document.createElement('canvas');
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    const context = canvas.getContext('2d');
    context.drawImage(bitmap, 0, 0);
    const imageData = context.getImageData(0, 0, bitmap.width, bitmap.height);
    return imageData;
}
 
/**
 * 
 * @param {string} selector 
 * @returns {Promise<ImageData>}
 */
export async function getBitmap(selector) {
    const element = document.querySelector(selector);
    if (element instanceof HTMLImageElement) {
        const bitmap = await createImageBitmap(element);
        return getBitmapFromImageSource(bitmap);
    }
}
 
/**
 * 
 * @param {ImageData} imageData
 * @return {string}
 */
export function imageDataToImage(imageData) {
    const canvas = document.createElement('canvas');
    canvas.width = imageData.width;
    canvas.height = imageData.height;
    const context = canvas.getContext('2d');
    context.putImageData(imageData, 0, 0);
    return canvas.toDataURL();
}
 
/**
 * 
 * @param {ImageData} imageData
 * @param {number} x 
 * @param {number} y
 * @return {Uint8ClampedArray}
 */
export function getPixel(imageData, x, y) {
    const pixel = y * imageData.width + x;
    const colorChannels = 4;
    return imageData.data.subarray(pixel * colorChannels, (pixel + 1) * colorChannels);
}
 
/**
 * 
 * @param {ImageData} imageData
 * @param {number} x 
 * @param {number} y
 * @param {Uint8ClampedArray} colors 
 */
export function setPixel(imageData, x, y, colors) {
    Iif (x < 0 || y < 0) {
        return;
    }
    Iif (x >= imageData.width || y >= imageData.height) {
        return;
    }
    const pixel = y * imageData.width + x;
    const colorChannels = 4;
    imageData.data.set(colors, pixel * colorChannels);
}