Convert to Binary
The goal of this function is to convert the loaded image into a binary format. It achieves this by applying a threshold to the brightness of each pixel in the image. Here’s the breakdown:
Get Image Data
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
Decide Whether Pixel is White or Black
for (let i = 0; i < data.length; i += 4) {
const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
const threshold = 128;
const color = brightness > threshold ? 255 : 0;
data[i] = data[i + 1] = data[i + 2] = color;
}
It calculates the brightness of each pixel using a weighted sum of its RGB values. If the brightness is greater than a threshold (128), it sets the pixel color to white (255); otherwise, it sets it to black (0).
Reverse Hex Color
The purpose of this function is to reverse the hex color of each pixel in the loaded image. It achieves this by subtracting each color component from 255. Here’s the breakdown:
Get Image Data
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
Reverse Hex Color
for (let i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i]; // Reverse Red
data[i + 1] = 255 - data[i + 1]; // Reverse Green
data[i + 2] = 255 - data[i + 2]; // Reverse Blue
}
It subtracts each color component (Red, Green, Blue) from 255, effectively creating a color negative.