Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active October 2, 2015 12:08
Show Gist options
  • Save williammalo/2241109 to your computer and use it in GitHub Desktop.
Save williammalo/2241109 to your computer and use it in GitHub Desktop.
Check if canvas pixel is black

This function checks if a canvas pixel is black.

This is very useful for making pixel-perfect collisions in a javascript game.

argument x and y are for the coordinates of said pixel.

argument c is for the canvas context.

function(x,y,c){return window[c].getImageData(x,y,1,1).data[1]<20}
function(x,y,c){return window[c].getImageData(x,y,1,1).data[1]<20}
{
"name": "PixCheck",
"description": "This function checks if a certain canvas pixel is black",
"keywords": [
"canvas",
"collision",
"pixel",
"data",
"html"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>undefined</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function(){ /* the code here should be identical to the entry. */ }
document.getElementById( "ret" ).innerHTML = myFunction()
</script>
@maettig
Copy link

maettig commented Apr 3, 2012

Doesn't this fail for all red, blue and magenta colored pixels? Also (I'm sure you know) it's very slow to call getImageData over and over again.

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