Home > Article > Web Front-end > How to Get the Pixel Color Under the Mouse Cursor on a Canvas?
Getting Pixel Color from Canvas on Mousemove
Introduction
Obtaining the precise pixel color beneath the mouse cursor on a canvas can be useful for various applications, such as image editing, pixel-based games, or color selection tools. This article will provide a comprehensive example that enables you to accomplish this task.
Steps to Get Pixel Color
Initial Canvas Setup:
Handle Mouse Movement:
Get Image Data:
Extract RGB Values:
Display Color:
Example Code:
Below is a complete example that demonstrates the steps outlined above:
<code class="html"><canvas id="my-canvas" width="200px" height="200px"></canvas> <div id="color-info"></div></code>
<code class="javascript">const canvas = document.getElementById('my-canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; ctx.fillRect(0, 0, 100, 100); canvas.addEventListener('mousemove', (e) => { const rect = canvas.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; const pixelData = ctx.getImageData(x, y, 1, 1).data; const colorInfo = `RGB: (${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]})`; document.getElementById('color-info').innerHTML = colorInfo; });</code>
In this example, the color-info div will display the RGB color values of the pixel under the mouse cursor as it moves across the canvas.
Additional Considerations
The above is the detailed content of How to Get the Pixel Color Under the Mouse Cursor on a Canvas?. For more information, please follow other related articles on the PHP Chinese website!