"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Get the Pixel Color from a Canvas on Mousemove?

How to Get the Pixel Color from a Canvas on Mousemove?

Published on 2024-11-02
Browse:864

How to Get the Pixel Color from a Canvas on Mousemove?

Get Pixel Color from Canvas on Mousemove

Overview

This post explores how you can retrieve the RGB values of the pixel under the mouse cursor while moving over a canvas element. We'll provide a comprehensive approach with a self-contained example.

Solution

To achieve this, first create a canvas with the desired dimensions:

Fill the canvas with elements such as squares:

const example = document.getElementById('example');
const ctx = example.getContext('2d');

ctx.fillStyle = randomColor();
ctx.fillRect(0, 0, 50, 50);

ctx.fillStyle = randomColor();
ctx.fillRect(55, 0, 50, 50);

ctx.fillStyle = randomColor();
ctx.fillRect(110, 0, 50, 50);

Finally, add the mousemove event handler that captures the pixel values at the cursor's position:

$('#example').mousemove(function(e) {
  // Calculate the position relative to the canvas
  const pos = findPos(this);
  const x = e.pageX - pos.x;
  const y = e.pageY - pos.y;
  const coord = `x=${x}, y=${y}`;

  // Get the pixel value
  const c = this.getContext('2d');
  const p = c.getImageData(x, y, 1, 1).data;

  // Convert to hex format
  const hex = "#"   ("000000"   rgbToHex(p[0], p[1], p[2])).slice(-6);

  // Display the color information
  $('#status').html(coord   "
" hex); });

Utility Functions

This code relies on supporting functions for finding the element's position and converting RGB values to hex. Define these functions as follows:

function findPos(obj) {
  let curleft = 0, curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft  = obj.offsetLeft;
      curtop  = obj.offsetTop;
    } while (obj = obj.offsetParent);
    return { x: curleft, y: curtop };
  }
  return undefined;
}

function rgbToHex(r, g, b) {
  if (r > 255 || g > 255 || b > 255) throw "Invalid color component";

  return ((r << 16) | (g << 8) | b).toString(16);
}

function randomInt(max) {
  return Math.floor(Math.random() * max);
}

function randomColor() {
  return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`;
}

Live Example

Visit the following link to see the full example in action:

https://bl.ocks.org/wayneburkett/ca41a5245a9f48766b7bc881448f9203

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3