spritemaker
Version:
Make image sprites quickly and easily
89 lines (79 loc) • 2.44 kB
JavaScript
const makeSprite = ({ sprite, name="sprite-table", interval=1000, pixelSize=1, parentId=""}) => {
const gridNode = makeGrid(sprite, name, pixelSize)
if (parent) {
const parent = document.getElementById(parentId)
parent.appendChild(gridNode)
}
const diffs = getDiffs(sprite)
return {
currentTimer: null,
sprite: gridNode,
start: function() {
this.currentTimer = startTimer(gridNode, diffs, interval)
},
stop: function() {
clearInterval(this.currentTimer)
},
}
}
const getDiffs = sprite => {
const pairs = getAdjacentPairs(sprite)
console.log(pairs.length)
return pairs.map(diff)
}
const diff = ([frame1, frame2]) => (
frame1.reduce((diffs, row, x) => (
[...diffs, ...row.reduce((acc, color, y) => (
color !== frame2[x][y] ? [...acc, [[x, y], frame2[x][y]]] : acc
), [])]
), [])
)
const getAdjacentPairs = arr => (
arr.reduce((pairs, el, idx) => (
idx === arr.length - 1
? [...pairs, [el, arr[0]]]
: [...pairs, [el, arr[idx + 1]]]
), [])
)
const makeGrid = (sprite, className, pixelSize) => {
const firstFrame = sprite[0]
const height = firstFrame.length
const width = firstFrame[0].length
const table = document.createElement("table")
table.classList.add(className)
table.style.display = "flex"
table.style.flexWrap = "wrap"
table.style.borderCollapse = "collapse"
table.style.height = `${pixelSize * height}px`
table.style.width = `${pixelSize * width}px`
firstFrame.forEach((spriteRow, x) => {
const row = document.createElement("tr")
spriteRow.forEach((color, y) => {
const cell = document.createElement("td")
cell.style.height = `${pixelSize}px`
cell.style.width = `${pixelSize}px`
cell.style.padding = 0
cell.style.margin = 0
cell.style.backgroundColor = color
row.appendChild(cell)
})
table.appendChild(row)
})
return table
}
const startTimer = (gridNode, diffs, interval) => {
const gridArray = Array.from(gridNode.children).map(row => (
Array.from(row.children)
))
const imageCount = diffs.length
let currentImageId = 0
const paint = () => {
const currentDiff = diffs[currentImageId]
currentDiff.forEach(([[x, y], color]) => {
gridArray[x][y].style.backgroundColor = color
})
currentImageId = (currentImageId + 1) % imageCount
}
return setInterval(paint, interval)
}
exports.makeSprite = makeSprite