Skip to content

Instantly share code, notes, and snippets.

@williammalo williammalo/README.md forked from 140bytes/LICENSE.txt
Last active Oct 8, 2015

Embed
What would you like to do?
image to 2d array

converts canvas image data to a 2d array of booleans

array=img2array(imagedata,width,height)

array[x][y] //gives true or false

very useful for games where you need pixel perfect collision.

Reading an image every time you check for collision is slow. Using a 2d array makes it much faster, and has a very simple syntax (array[x][y]) .

Game engine using image to 2d array conversion: http://maloweb.com/snippets/terraindemo

function(a,w,h,i,j,l){
l=[]; //initiate array
for(i=0;i<w;i++){ //loop through all x positions
l[i]=[]; //make a new array
for(j=0;j<h;j++) //loop through all y positions
l[i][j]=a[j*w+i<<2]<128 //fill l[x][y] with boolean (with a black and white image, black is true, white is false)
}
return l //return the array
}
function(a,w,h,i,j,l){l=[];for(i=0;i<w;i++){l[i]=[];for(j=0;j<h;j++)l[i][j]=a[j*w+i<<2]<128}return l}
{
"name": "img2array",
"description": "converts an canvas image data to a 2d array of booleans",
"keywords": [
"canvas",
"image",
"2d",
"array"
]
}
<!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>
@tsaniel

This comment has been minimized.

Copy link

commented Aug 17, 2012

(j*w+i)*4 -> j*w+i>>2?

@williammalo

This comment has been minimized.

Copy link
Owner Author

commented Aug 20, 2012

@tsaniel you mean j*w+i<<2 ?
Good idea! Thanks!

@tsaniel

This comment has been minimized.

Copy link

commented Aug 21, 2012

Yes! Sorry for the mistake.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.