I have built an infinite text carousel animation using HTML Canvas. You can see how the animation works here: https://codepen.io/m1llipede/pen/zYdLBBP
Essentially, I am adding a new quote to a display array after the previous quote reaches a specific point on the canvas:
// if this quote is at the top of canvas
if (Math.floor(this.y) == 80 && this.callNextQuote) {
// call next quote
addToDisplayArr()
// set flag so this wont run again
this.callNextQuote = false
}
Then I am removing that quote from the display array when the quote has left the bottom of the canvas:
// if this quote has reached the end of the canvas
if (this.y > ctx.canvas.height + 50 && this.removedQuote == false) {
// remove this quote from display arr
removeFromDisplayArr()
// set flag so this wont run again
this.removedQuote = true
}
I am also animating the opacity of each quote - fading them in as they reach the center of the canvas then fading them out as the reach the bottom. Here is were the bug is occuring. You will notice that each time a new quote object is added to the display array. the first quote in the array seems to have its opacity set back to zero. This is causing the unwanted flashing on the first quotes that animate on the canvas.
Here is where I am handling adding/removing quotes:
// one by one push item from api to display array
function addToDisplayArr() {
// reset index is we've reached all quotes from API
if (lastIndex == quoteData.length) {
lastIndex = 0
}
// create new quote object and add it to display array
displayArr.push(new Quote(quoteData[lastIndex].message, quoteData[lastIndex].name));
// increase to next index
lastIndex++
}
// remove quote from display array once it has left the screen
function removeFromDisplayArr() {
displayArr.shift()
console.log('removed:', displayArr, lastIndex)
}
Could this be an issue with how I am adding new quotes to the display array? If so how should I be adding new quotes without affecting the rendering of the other quotes?
Another note: in production this will be getting quotes from an API that will refresh over time as the animation runs, pulling in new quotes as they are added to the database.