When making HTML5 games, we can animate by using a single file with lots of images on it (I think this is called a sprite image?) instead of sending multiple images in multiple files. We erase the image in canvas and redraw it, changing the position of the sprite file, thus changing the image and giving the animation effect.
My question is, how can we quickly find the pixel position to redraw the image and draw the part of the sprite file we want? Because we need to pinpoint the exact position, down to a single pixel accuracy. How can we do that without a lot of trial and error?
The exact [left,top] positions of every individual sprite on a spritesheet are always fully known by it's creator. That really is the essential property of a spritesheet.
If you have the creator's code, you might examine the code to get the positions of the individual sprites.
If you don't have the creator's mapping coordinates and the sprites appear to be arranged in a grid pattern (rows & columns), you can often correctly guess the mappings like this:
var spriteWidth = spriteSheetWidth / spriteCountPerRow;
var spriteHeight = spriteSheetHeight / spriteCountPerColumn;
Many spritesheets are not arranged in a grid pattern, but rather are arranged to allow as many sprites as possible to exist in as small an image size as possible.
If you just have the spritesheet without code, then you can find the bounding box of each sprite by using edge detection. Here's an outline of how to do it:
context.getImageData
to get the RGBA information of all pixels on the canvas.Scan the [x,y] in step#3 to find the bounding box of the sprite.
The minimum x will be the leftmost coordinate of the bounding box.
The minimum y will be the topmost coordinate of the bounding box.
The maximuinimum x will be the leftmost coordinate of the bounding box.
The minimum y will be the topmost coordinate of the bounding box.