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:
- Use
context.getImageData
to get the RGBA information of all pixels on the canvas.
- Start at the top-left of the canvas and find the first pixel that is not the background color. This will be one pixel of an individual sprite.
- Use the "Marching Squares" algorithm to find the [x,y] of all the pixels around the border of that sprite. Here's a previous Stackoverflow post showing how to implement Marching Squares: Draw border around nontransparent part of image on 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.
- We're done with the discovered sprite, so erase the bounding box of the discovered sprite.
- Go back to step#1 to find the next sprite.