HTML5 Game - Accessing pixel values from image

Description

Accessing pixel values from image

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    /*ww  w.java  2  s .  c o m*/
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        // Accessing the first pixel
        let image = new Image();
        image.src = "http://java2s.com/style/demo/jet2.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0, 500, 333);
          
          let imageData = context.getImageData(0, 0, 3, 3); // 3x3 grid
          let pixel = imageData.data; // CanvasPixelArray
          
          let red = pixel[0];
          let green = pixel[1];
          let blue = pixel[2];
          let alpha = pixel[3];
        });
      
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

CanvasPixelArray returns an array which is one long array of RGBA color values.

Each pixel has four values.

The top left pixel is at the start of the array (from positions 0, red, to 3, alpha).

The bottom right pixel is at the end of the array.

The pixels go in a left to right direction until they reach the end of a row, then return to the beginning of the next row and go from left to right again.

The following formula can get exactly the right pixel that you want from a CanvasPixelArray.

     
let imageData = context.getImageData(0, 0, 3, 3); // 3x3 grid  
     
let width = imageData.width;  
let x = 2;  
let y = 2;  
     
let pixelRed = ((y-1)*(width*4))+((x-1)*4);  
let pixelGreen = pixelRed+1;  
let pixelBlue = pixelRed+2;  
let pixelAlpha = pixelRed+3;  

Related Topic