Get pixel color from canvas with HTML

To get the pixel color from a canvas element in HTML, you need to access the canvas pixel data using the getImageData() method. This method returns an ImageData object containing the RGBA values for each pixel, which you can then use to extract specific pixel colors.

Syntax

Following is the syntax to get pixel color from canvas −

var imageData = context.getImageData(x, y, width, height);
var data = imageData.data;
var index = (Math.floor(y) * canvasWidth + Math.floor(x)) * 4;

The getImageData() method returns an ImageData object with a data property containing pixel information in RGBA format.

Parameters

  • x, y − The coordinates of the pixel you want to get the color from
  • width, height − The dimensions of the image data area (use 1, 1 for single pixel)
  • canvasWidth − The width of the canvas element
  • data − The pixel data array from ImageData object
  • index − The calculated position in the data array

How It Works

The canvas stores pixel data as a one-dimensional array where every four consecutive values represent one pixel's RGBA components. To get a specific pixel's color, you calculate its position in this array using the formula −

var index = (Math.floor(y) * canvasWidth + Math.floor(x)) * 4;

// Extract RGBA values
var r = data[index];     // Red component (0-255)
var g = data[index + 1]; // Green component (0-255)
var b = data[index + 2]; // Blue component (0-255)
var a = data[index + 3]; // Alpha component (0-255)

Basic Example

Following example demonstrates how to get pixel color from a canvas when clicking on it −

<!DOCTYPE html>
<html>
<head>
   <title>Get Pixel Color from Canvas</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <canvas id="myCanvas" width="300" height="200" style="border: 1px solid black; cursor: crosshair;"></canvas>
   <p id="colorInfo">Click on the canvas to get pixel color</p>
   
   <script>
      var canvas = document.getElementById('myCanvas');
      var ctx = canvas.getContext('2d');
      
      // Draw some colored rectangles
      ctx.fillStyle = 'red';
      ctx.fillRect(0, 0, 100, 100);
      ctx.fillStyle = 'green';
      ctx.fillRect(100, 0, 100, 100);
      ctx.fillStyle = 'blue';
      ctx.fillRect(200, 0, 100, 100);
      ctx.fillStyle = 'yellow';
      ctx.fillRect(0, 100, 150, 100);
      ctx.fillStyle = 'purple';
      ctx.fillRect(150, 100, 150, 100);
      
      canvas.addEventListener('click', function(event) {
         var rect = canvas.getBoundingClientRect();
         var x = event.clientX - rect.left;
         var y = event.clientY - rect.top;
         
         var imageData = ctx.getImageData(x, y, 1, 1);
         var data = imageData.data;
         
         var r = data[0];
         var g = data[1];
         var b = data[2];
         var a = data[3];
         
         document.getElementById('colorInfo').innerHTML = 
            'Pixel at (' + Math.floor(x) + ', ' + Math.floor(y) + '): ' +
            'RGB(' + r + ', ' + g + ', ' + b + ') Alpha: ' + a;
      });
   </script>
</body>
</html>

Click anywhere on the canvas to see the RGBA values of that pixel displayed below −

[Canvas with colored rectangles - red, green, blue on top row; yellow and purple on bottom]
Pixel at (50, 50): RGB(255, 0, 0) Alpha: 255

Advanced Example with Color Picker

Following example creates a more advanced color picker that displays the color in different formats −

<!DOCTYPE html>
<html>
<head>
   <title>Canvas Color Picker</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <canvas id="colorCanvas" width="400" height="300" style="border: 2px solid #333; cursor: crosshair;"></canvas>
   <div style="margin-top: 10px; padding: 10px; background: #f5f5f5; border-radius: 5px;">
      <p id="coordinates">Position: (0, 0)</p>
      <p id="rgbaColor">RGBA: (0, 0, 0, 0)</p>
      <p id="hexColor">HEX: #000000</p>
      <div id="colorPreview" style="width: 50px; height: 50px; border: 1px solid #000; display: inline-block; margin-left: 10px;"></div>
   </div>
   
   <script>
      var canvas = document.getElementById('colorCanvas');
      var ctx = canvas.getContext('2d');
      
      // Create a gradient background
      var gradient = ctx.createLinearGradient(0, 0, 400, 300);
      gradient.addColorStop(0, '#ff0000');
      gradient.addColorStop(0.2, '#ff8000');
      gradient.addColorStop(0.4, '#ffff00');
      gradient.addColorStop(0.6, '#00ff00');
      gradient.addColorStop(0.8, '#0080ff');
      gradient.addColorStop(1, '#8000ff');
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, 400, 300);
      
      // Add some circles
      ctx.fillStyle = 'white';
      ctx.beginPath();
      ctx.arc(100, 100, 30, 0, 2 * Math.PI);
      ctx.fill();
      ctx.fillStyle = 'black';
      ctx.beginPath();
      ctx.arc(300, 200, 25, 0, 2 * Math.PI);
      ctx.fill();
      
      function componentToHex(c) {
         var hex = c.toString(16);
         return hex.length == 1 ? "0" + hex : hex;
      }
      
      function rgbToHex(r, g, b) {
         return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
      }
      
      canvas.addEventListener('mousemove', function(event) {
         var rect = canvas.getBoundingClientRect();
         var x = Math.floor(event.clientX - rect.left);
         var y = Math.floor(event.clientY - rect.top);
         
         var imageData = ctx.getImageData(x, y, 1, 1);
         var data = imageData.data;
         
         var r = data[0];
         var g = data[1];
         var b = data[2];
         var a = data[3];
         
         document.getElementById('coordinates').textContent = 'Position: (' + x + ', ' + y + ')';
         document.getElementById('rgbaColor').textContent = 'RGBA: (' + r + ', ' + g + ', ' + b + ', ' + (a/255).toFixed(2) + ')';
         document.getElementById('hexColor').textContent = 'HEX: ' + rgbToHex(r, g, b);
         document.getElementById('colorPreview').style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
      });
   </script>
</body>
</html>

Move your mouse over the canvas to see real-time color information and preview −

[Canvas with gradient background and white/black circles]
Position: (150, 120)
RGBA: (255, 191, 0, 1.00)
HEX: #ffbf00
[Color preview square showing the selected color]

Error Handling

When working with canvas pixel data, you may encounter security restrictions. If the canvas contains images from different domains, getImageData() will throw a security error. Always handle this case −

try {
   var imageData = ctx.getImageData(x, y, 1, 1);
   var data = imageData.data;
   // Process pixel data...
} catch (e) {
   console.error('Cannot access pixel data: ', e.message);
}
Canvas Pixel Data Structure [R, G, B, A, R, G, B, A, R, G, B, A, ...] ImageData.data array R data[0] G data[1] B data[2] A data[3] First Pixel R data[4] G data[5] B data[6] A data[7] Second Pixel Index = (y × canvasWidth + x) × 4 Each pixel occupies 4 consecutive array positions
Updated on: 2026-03-16T21:38:53+05:30

387 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements