Skip to content

Instantly share code, notes, and snippets.

@rlemon

rlemon/paint.md Secret

Created July 29, 2015 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlemon/becc5f71c506b5353a79 to your computer and use it in GitHub Desktop.
Save rlemon/becc5f71c506b5353a79 to your computer and use it in GitHub Desktop.

well if you want to know the x,y of the pixels in the canvas you can use a loop like the following:

var image = context.getImageData(0, 0, width, height),
    data = image.data;
for( var x = 0; x < width; x++ ) {
  for( var y = 0; y < height; y++) {
    var i = (x*4)+(y*4*image.width);
    data[i] = ..; // I am the red
    data[i+1] = ..; // I am the green
    data[i+2] = ..; // I am the blue
    data[i+3] = ..; // I am the alpha
  }
}

if x/y positioning isn't important you can reduce it to a single loop (same setup as before).

for( var i = 0; i < data.length; i+=4) {
  data[i] = ..; // I am the red
  data[i+1] = ..; // I am the green
  data[i+2] = ..; // I am the blue
  data[i+3] = ..; // I am the alpha
}

then you want to re-paint the image to the canvas.

context.putImageData(image, 0, 0); putImageData is a little expensive however if you are manipulating gradients this seems to be the quickest route I have found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment