I have a program that keeps track of a number. If you get above your goal number, you visit a page that shows how much extra you have stored up. On that page is a gumball machine, and depending on the number of excess you have stored up, a certain number of gumballs appear in side the machine. Everything works fine, but about 1 out of every 3 page loads, the gumballs appear first, and then the machine appears, covering all of the gumball images first.
This is being done through vue.js Here is the code I have:
created () {
this.$http.get('/gumballs/' + this.$auth.user().id).then(res => {)
this.createCanvas()
})
}
*******
createCanvas () {
// general canvas properties...
// gumball machine properties
this.createGumbllMachine(canvas.width, ctx, (err, succ) => {
if (err) {
console.log(err)
} else if (succ) {
this.createGumballs(canvas.width, ctx)
}
})
}
**********
createGumballMachine (width, ctx, cb) {
const imgObj = document.createElement('img')
imgObj.src = machineImg
imgObj.onload = () => {
ctx.drawImage(imgObj, (width / 2) - 350, 100)
}
return cb(null, 'ok')
}
I have tried to use a callback function as the last argument in createGumballMachine()
so that the machine is drawn first and then the gumballs are drawn afterwards, but this doesn't work.
I also tried using async
and await
but I coudn't get the image to render at all that way. Something was happening where vue could never get past the created
portion of it's lifecycle.
I have tried reading about this on other SO questions, but I can't figure it out. I know it has something to do the way ctx.dtawImage()
works, but I'm stuck.
Any help is appreciated. If you need to see the code for createGumballs()
let me know, but I don't see how that is causing the problem.