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
  • 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>
@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