Skip to content

Instantly share code, notes, and snippets.

@tacyarg
Created April 15, 2019 15:04
Show Gist options
  • Save tacyarg/111e5f3bc2d28bf19631b73bf86a5ba6 to your computer and use it in GitHub Desktop.
Save tacyarg/111e5f3bc2d28bf19631b73bf86a5ba6 to your computer and use it in GitHub Desktop.
how to animate a sprite sheet
export default ({ imageurl, width = 200, height = 200, scale = 1 }) => {
let img = new Image()
img.src = imageurl
img.onload = loop()
let canvas = document.querySelector('canvas')
let ctx = canvas.getContext('2d')
const scaledWidth = scale * width
const scaledHeight = scale * height
function drawFrame(frameX, frameY, canvasX, canvasY) {
ctx.clearRect(0, 0, width, height)
ctx.drawImage(
img,
frameX * width,
frameY * height,
width,
height,
canvasX,
canvasY,
scaledWidth,
scaledHeight
)
}
const columns = 10
const rows = 12
let frameCount = 0
let currentColumn = 0
let currentRow = 0
function step() {
frameCount++
if (frameCount < 2) {
window.requestAnimationFrame(step)
return
}
frameCount = 0
drawFrame(currentColumn++, currentRow, 0, 0)
if (currentColumn >= columns) {
currentColumn = 0
currentRow++
}
if (currentRow >= rows) {
currentRow = 0
}
window.requestAnimationFrame(step)
}
function loop() {
window.requestAnimationFrame(step)
}
return {
step,
loop
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment