Spritesheet generator improvements

This commit is contained in:
Dennis Postma 2024-12-15 17:39:47 +01:00
parent 65cae5d824
commit a8934f8e40

View File

@ -129,32 +129,41 @@ export default class SpriteUpdateEvent {
await Promise.all(
processedActions.map(async ({ action, buffersWithDimensions, frameWidth, frameHeight }) => {
// Get and validate all frame dimensions first
const frames = await Promise.all(
// First prepare each frame with exact dimensions
const centeredFrames = await Promise.all(
buffersWithDimensions.map(async ({ buffer }) => {
// Get the current dimensions
const metadata = await sharp(buffer).metadata()
return {
buffer,
width: metadata.width!,
height: metadata.height!
}
const width = metadata.width!
// Calculate padding to center the sprite
const leftPadding = ((frameWidth - width) >> 1)
return await sharp(buffer)
.extend({
top: 0,
bottom: 0,
left: leftPadding,
right: frameWidth - width - leftPadding,
background: { r: 0, g: 0, b: 0, alpha: 0 }
})
.toBuffer()
})
)
// Combine the frames
const combinedImage = await sharp({
create: {
width: frameWidth * frames.length,
width: frameWidth * centeredFrames.length,
height: frameHeight,
channels: 4,
background: { r: 0, g: 0, b: 0, alpha: 0 }
}
})
.composite(
frames.map(({ buffer, width, height }, index) => ({
centeredFrames.map((buffer, index) => ({
input: buffer,
// Center horizontally based on the exact middle of each frame
left: (index * frameWidth) + ((frameWidth - width) >> 1),
// Top position is always 0
left: index * frameWidth,
top: 0
}))
)