Sir
Sir

Reputation: 8280

Image data in JS

I want to know if I've understood this correctly.

I loop my map and load sprites on the map.

So I decided to store the pixel information in an array so that when I click with my mouse I check if its in a pixel array range and get the id related to it (effectively being pixel accurate for detecting what object was clicked?)

This is my thinking process:

I draw the sprite:

ctx.drawImage(castle[id], abposx, abposy - (imgheight/2));  
myImageData[sdata[i][j][1]] = 
      ctx.getImageData(abposx, abposy, castle[id].width, castle[id].height);

Then some how with left click, check if mouse x and mouse y is inbetween the range of the arrays and return the value of myImageData?

Or have I misunderstood what getImageData is about?

Upvotes: 0

Views: 170

Answers (1)

Loktar
Loktar

Reputation: 35309

getImageData gives you all of the pixel data for an image. Basically you only need to use getImageData if you are doing any sort of pixel manipulation with the image, like changing its hue/color, or applying a filter, or need specific data, such as the r/g/b, or alpha values. In order to check for pixel perfect collisions you an do something like the following:

    var imageData = ctx.getImageData(x, y, 1, 1);
    if(imageData.data[3] !== 0){
        // you have a collision!
    }

imageData.data[0-3] holds an array of data, 0-2 are the color values r/g/b, and 3 is the alpha value. So we assume if the alpha is 0, it must be a transparent portion. Also note, in the example and fiddle I am grabbing the data from the canvas itself, so if there was an image behind it that wasnt transparent it would count as not being transparent. The best way to do it if you have many images that overlap is to keep a copy of the image by itself offscreen somewhere and do a translation of the coordinates to get the position on the image. Heres a good MDN Article explaining getImageData as well.

Live Demo

Upvotes: 2

Related Questions