Get pixel color from an image [duplicate]

  • Create a canvas document.createElement
  • Get the 2d context canvas.getContext('2d')
  • Draw the image to the canvas context.drawImage(image, x, y)
    • Make sure the image is from the same domain or you won’t have access to its pixels
  • Get the pixel data for the image context.getImageData(x1, y1, x2, y2)
    • You want just the top left so context.getImageData(0, 0, 1, 1)
  • The result of getImageData will have an array of pixels in it’s data field (context.getImageData(0,0,1,1).data)
    • The array will have r, g, b and a values.

Leave a Comment