Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active September 24, 2022 23:45
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 williammalo/3370965 to your computer and use it in GitHub Desktop.
Save williammalo/3370965 to your computer and use it in GitHub Desktop.
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
Copy link

tsaniel commented Aug 17, 2012

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

@williammalo
Copy link
Author

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

@tsaniel
Copy link

tsaniel commented Aug 21, 2012

Yes! Sorry for the mistake.

@MoAboabdo
Copy link

what if have real image data and want to convert it to a 2d array but fill it with data, not booleans?

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