Home  >  Article  >  Web Front-end  >  How to Get the Pixel Color from a Canvas on Mousemove?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 10:03:01217browse

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:

<code class="html"><canvas id="example" width="200" height="60"></canvas></code>

Fill the canvas with elements such as squares:

<code class="js">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);</code>

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

<code class="js">$('#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 + "<br>" + hex);
});</code>

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:

<code class="js">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)})`;
}</code>

Live Example

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

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

The above is the detailed content of How to Get the Pixel Color from a Canvas on Mousemove?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn