Skip to content

Instantly share code, notes, and snippets.

@gkoberger
Created September 20, 2012 02:54
Show Gist options
  • Select an option

  • Save gkoberger/3753689 to your computer and use it in GitHub Desktop.

Select an option

Save gkoberger/3753689 to your computer and use it in GitHub Desktop.

Revisions

  1. gkoberger created this gist Sep 20, 2012.
    41 changes: 41 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    // Create a new image
    var image = new Image();
    var imageData = false;
    image.crossOrigin = '';
    image.src = 'http://p.gkoberger.net/firefox/firefox.png';

    // When it loads, we’re going to put it into a canvas element
    image.onload = function () {
    var cnvs = document.createElement('canvas');
    cnvs.width = image.width;
    cnvs.height = image.height;

    document.getElementsByTagName('body')[0].appendChild(cnvs);

    // This gives the drawing methods we need.
    var ctx = cnvs.getContext('2d');
    ctx.drawImage(image, 0, 0);

    // Only some browsers support getImageData.
    try {
    imageData = ctx.getImageData(0, 0, cnvs.width, cnvs.height);
    } catch (e) {
    alert("Your browser doesn’t support");
    return;
    }
    };

    // Returns RGBA
    function getColor(x, y) {
    if (!imageData) return;

    // Weird math to get the index; just trust me on this one
    var index = (y * imageData.width + x) * 4,
    red = imageData.data[index],
    green = imageData.data[index + 1],
    blue = imageData.data[index + 2],
    alpha = imageData.data[index + 3];

    // I’m returning RGBA, since it’s something we can use when writing HTML
    return "rgba(" + red + "," + green + "," + blue + "," + alpha + ");";
    }