Back to Forum
Pokemon - Image per frame stacked
frakeit posted 4 years ago
hi, im facing issue with draw image it's stacked each frame
how it's looks like : https://youtube.com/shorts/00SFgVICQoc
class Sprite {
constructor({
position,
image,
frames = {
max: 1,
hold: 10
},
animate = false,
}) {
this.position = position
this.image = image
this.frames = {
...frames,
val: 0,
elapsed: 0
}
this.image.onload = () => {
this.width = this.image.width / this.frames.max
this.height = this.image.height
}
this.animate = animate
}
draw() {
c.drawImage(
this.image, // img
this.frames.val * this.width, // sx
0, // sy
this.image.width / this.frames.max, // swidth
this.image.height, // sheight
this.position.x, // x
this.position.y, // y
this.image.width / this.frames.max, // width
this.image.height // height
)
if (!this.animate) return
if (this.frames.max > 1) {
this.frames.elapsed++
}
if (this.frames.elapsed % this.frames.hold === 0) {
if (this.frames.val < this.frames.max - 1) this.frames.val++
else this.frames.val = 0
}
}
}
//
const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')
canvas.width = 1024
canvas.height = 576
c.fillStyle = 'white'
c.fillRect(0, 0, canvas.width, canvas.height)
const draggleImage = new Image()
draggleImage.src = './img/draggleSprite.png'
const draggle = new Sprite({
position: {
x: 700,
y: 150
},
image: draggleImage,
frames: {
max: 4,
hold: 40
},
animate: true
})
renderedSprites = [draggle]
function animate() {
window.requestAnimationFrame(animate)
renderedSprites.forEach((sprite) => {
sprite.draw()
})
}
animate()chris posted 4 years ago
I believe you'll want to clear your canvas before each sprite draw with:
c.clearRect(0, 0, canvas.width, canvas.height)This'll give you a clean slate to draw on for each frame of your animation loop, effectively resolving the "stacking" issue you were mentioning.
Let me know if that works (thanks for the video by the way, makes it super helpful for debugging).
Want to participate?
Create a free Chris Courses account to begin