Canvas is flickering, img.src access

Viewed 41

I got a game with falling pics I push() the next func into an array and my pics var bulletinare flickering, so I think it's probably I draw them a lot when use update() func

function rect () {
    this.size = [rectSize.x, rectSize.y];
    this.imagesSrc = rand(0, 1) ? 'bulletinYes' : 'bulletinNo';
    this.position = [rand(0, w-rectSize.x), -rectSize.y];
    this.bulletinValue = (this.imagesSrc === 'bulletinYes') ? 'bulletinYesValue' : 'bulletinNoValue';
}

rect.prototype = {
    draw: function (){ 
        var bulletin = new Image();
        bulletin.src = imagesSrc[this.imagesSrc];
        ctx.drawImage(bulletin, this.position[0], this.position[2], this.size[0], this.size[2]);
    }
}

I've tried to put var bulletin outside the fuction like so

var bulletin = new Image();
bulletin.src = imagesSrc[this.imagesSrc];   <= ???
function rect () {
    this.size = [rectSize.x, rectSize.y];
    this.imagesSrc = rand(0, 1) ? 'bulletinYes' : 'bulletinNo';
    this.position = [rand(0, w-rectSize.x), -rectSize.y];
    this.bulletinValue = (this.imagesSrc === 'bulletinYes') ? 'bulletinYesValue' : 'bulletinNoValue';
}

rect.prototype = {
    draw: function (){ 
        ctx.drawImage(bulletin, this.position[0], this.position[1], this.size[0], this.size[1]);
    }
}

but I have no idea how to change [this..imagesSrc] so it could work. And also it is executed only once and pic are not randomizing for each pushed one. Does anyone have any suggestion how to get rid of the flickering or change bulletin.src = imagesSrc[this.imagesSrc];

here's my github link if u want to see whole script

I just started my coding path, so thanks anyone who could answer this one:)

1 Answers

You create new image each time and trying to draw it before image is loaded. Better way is prepare all images at start and just draw it. Little changes in your code and all will work:

Prepare images:

var imagesSrc = {
    ballotBoxImgSrc: 'img/ballotBox.png',
    bulletinYes: 'img/yes.jpg',
    bulletinNo: 'img/no.jpg'
};

var images = {
    ballotBoxImgSrc: new Image(),
    bulletinYes: new Image(),
    bulletinNo: new Image()
}
for(let [name,value] of Object.entries(imagesSrc)) {
    images[name].src = value;
}

Draw:

rect.prototype = {
    draw: function (){ 
        var bulletin = images[this.imagesSrc];
        ctx.drawImage(bulletin, this.position[0], this.position[1], this.size[0], this.size[1]);        
    }
}
Related