get color at pointer in javascript

You can use a combination of DOM manipulation and event listeners to get the color at a pointer in JavaScript. Here's an example of how to do it:

HTML

<div id="color-picker"></div>
30 chars
2 lines

JavaScript

index.tsx
const colorPicker = document.getElementById("color-picker");

// Add a mousemove event listener to the color picker
colorPicker.addEventListener("mousemove", function(event) {
  // Get the x and y coordinates of the pointer
  const x = event.offsetX;
  const y = event.offsetY;

  // Get the color at the pointer by creating a 1x1 pixel canvas and getting its color
  const canvas = document.createElement("canvas");
  canvas.width = 1;
  canvas.height = 1;
  const ctx = canvas.getContext("2d");
  ctx.drawImage(colorPicker, -x, -y);
  const pixelData = ctx.getImageData(0, 0, 1, 1).data;

  // Convert the color data into a hex string and display it
  const colorString = "#" + ("000000" + rgbToHex(pixelData[0], pixelData[1], pixelData[2])).slice(-6);
  colorPicker.style.backgroundColor = colorString;
});

// Helper function to convert RGB values to hexadecimal
function rgbToHex(r, g, b) {
  return ((r << 16) | (g << 8) | b).toString(16);
}
948 chars
26 lines

This code creates a div that serves as a color picker and adds a mousemove event listener to it. When the user moves their mouse over the color picker, the code retrieves the (x, y) coordinates of the pointer and creates a small (1x1 pixel) canvas. The canvas is used to get the color at the pointer by copying a 1-pixel area of the color picker image onto the canvas and then retrieving the color data of that pixel. Finally, the color data is converted into a hex string (using the rgbToHex function) and used to set the background color of the color picker div.

gistlibby LogSnag