HTML and CSS Reference
In-Depth Information
jsonOutput
=
{};
for
(
var
spriteName
in
rowData) {
// Order by ascending number
var
row
=
rowData[spriteName].sort(
function
(a,b) {
return
a[0]
-
b[0];
}),
firstImage
=
row[0][1],
imageWidth
=
firstImage.width,
rowHeight
=
firstImage.height,
rowWidth
=
Math.min(imageWidth
*
row.length, maxSpriteWidth),
cols
=
Math.floor(rowWidth
/
imageWidth),
rows
=
Math.ceil(row.length
/
cols);
jsonOutput[spriteName]
=
{ sx
:
0, sy
:
curY, cols
:
cols,
tilew
:
imageWidth, tileh
:
rowHeight,
frames
:
row.length };
for
(
var
i
=
0;i
<
rows;i
++
) {
for
(
var
k
=
0;k
<
cols;k
++
) {
if
(row[k
+
i
*
cols]) {
ctx.drawImage(row[k
+
i
*
cols ][1],k
*
imageWidth,curY);
}
}
curY
+=
rowHeight;
}
}
return
jsonOutput;
}
The
drawImages
method takes in the rows' data and the Canvas and then loops over each row. For each
row, it calls the JavaScript
sort
method with a method that sorts images by the first element of the array. It
then grabs the first image from each row to calculate the height of the row and the width of each row.
Armed with this information, it can create the
jsonOutput
entry for this row based on the width and height
of each frame and the current
y
location on the Canvas (stored in
curY
).
The code then loops over each image in the row, based on the number of rows and columns for that sprite,
and draws it at the correct
x
and
y
location, updating
curY
to keep each row of the sprite and each sprite at the
correct
y
location.
Updating and Running the Script
With
drawImages
written,
spriter.js
is now complete; however, the script file in
bin/spriter
needs
to be updated to pass in the directory passed to it. Modify
bin/spriter
to match the code in
Listing 8-10
.
Listing 8-10:
An updated script