HTML and CSS Reference
In-Depth Information
Calculating the Size of the Canvas
Next is the method to calculate the size of the Canvas. This method's job is to add the height of each row of im-
ages, find the size of the largest row, and use that as the width of the resultant sprite map image. The largest row
is used because images need to be square in size. Add the code in Listing 8-8 to the bottom of spriter.js .
Listing 8-8: Calculating the image size in calculateSize
var maxSpriteWidth = 1024;
function calculateSize(rowData) {
var maxWidth = 0,
totalHeight = 0;
for(var spriteName in rowData) {
// Order by ascending number
var row = rowData[spriteName],
firstImage = row[0][1],
width = firstImage.width * row.length,
rows = 1;
if(width > maxSpriteWidth) {
rows = Math.ceil(width / maxSpriteWidth);
width = maxSpriteWidth;
}
maxWidth = Math.max(width,maxWidth);
totalHeight += firstImage.height * rows;
}
return { width: maxWidth, height: totalHeight };
}
This fairly simple method loops over the rows, grabs the first image from each row (remember each image in
a row is expected to be the same size), and then uses that image's height as the height of the row and the width
of the image multiplied by the number of images as the width of the row. It also uses the Math.max to pull out
the maximum row width as the final width of the image. Next, it checks if the resultant image is wider than the
maximum sprite width; if so it calculates the number of rows for the sprite and sets the width of the final sprite
to the maximum width. Finally, it returns an object with the calculated width and height.
Drawing Images on the Server-Side Canvas
All that's left to do, referring back to Listing 8-6 , is to write the drawImages method, which takes in the rows
data and the created Canvas, draws the images in rows , and then returns the jsonOutput that will be used
by your game engine to output.
This is actually simpler than it might seem because drawing an image to Canvas is a single call to
drawImage . The only thing you need to be careful about is to sort each row of data by its image index to pre-
vent sprites from showing up in the wrong order. Add the code in Listing 8-9 to the bottom of spriter.js .
Listing 8-9: Creating drawImages
function drawImages(rowData,canvas) {
var ctx = canvas.getContext('2d'),
curY = 0,
 
 
 
 
 
Search WWH ::




Custom Search