Skip to content

Instantly share code, notes, and snippets.

@appletreeat56
Created November 4, 2022 16:09
Show Gist options
  • Save appletreeat56/4a845f3ca8cde84093afa8734446b37c to your computer and use it in GitHub Desktop.
Save appletreeat56/4a845f3ca8cde84093afa8734446b37c to your computer and use it in GitHub Desktop.
<canvas id="myCanvas"> </canvas>
<script>
let img = new (window as any).Image();
img.crossOrigin = `Anonymous`;
img.src = "https://images.unsplash.com/photo-1667461143891-d52ffd5500f5";
img.onload = function () {
canvas = document.getElementById("myCanvas") as HTMLCanvasElement;
canvas.width = img.width;
canvas.height = img.height;
let ctx: CanvasRenderingContext2D = canvas.getContext(
"2d"
) as CanvasRenderingContext2D;
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imgData.data;
canvas.addEventListener("mousemove", (ev) => {
//as the mouse moves around the image
let cols = canvas.width;
let { offsetX, offsetY } = ev;
//call the method to get the r,g,b,a values for current pixel
let c = extractPixelColor(cols, offsetY, offsetX);
//build a colour string for
let colour = `rgb(${c.red}, ${c.green}, ${c.blue})`} ;
let hexCode = `#${[c.red, c.green, c.blue]
.map((x) => x.toString(16).padStart(2, "0"))
.join("")}`;
});
};
//cols: Width of the image representing total number of columns
//x: Row position of this pixel
//y: Column position of this pixel
const extractPixelColor = (cols: number, x: number, y: number) => {
//To get the exact pixel, the logic is to multiply total columns in this image with the row position of this pixel and then add the column position of this pixed
let pixel = cols * x + y;
//To get the array position in the entire image data array, simply multiply your pixel position by 4 (since each pixel will have its own r,g,b,a in that order)
let position = pixel * 4;
//the rgba value of current pixel will be the following
return {
red: data[position],
green: data[position + 1],
blue: data[position + 2],
alpha: data[position + 3],
};
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment