Tom Davies
Tom Davies

Reputation: 161

Draw two images onto HTML canvas in a specific order

I've written a function which draws two images, textBG and strap, onto a canvas. TextBG is a background, whilst strap is a logo to go on top of the background.

Annoyingly, however, there doesn't seem to be any specific order in which the two images are drawn onto the canvas, so the background will often be drawn on top of the logo.

Can anyone help me determine a way of ensuring that the first image, textBG, is loaded before the strap image, and therefore doesn't obscure it?

Javascript

function addTextBg(){

    var colourInput = document.getElementById("bgColour").value;
    if(colourInput > 2){
        var colour = 'red';
    }else if(colourInput > 1){
        var colour = 'pink';
    }else if(colourInput > 0){
        var colour = 'blue';
    }else{
        var colour = 'white';
    }
    var opacity = document.getElementById("bgOpacity").value;
    var size = document.getElementById("bgSize").value;
    var alignment = document.getElementById("bgAlign").value;
    if(colourInput > 0){
        var strapColour = 'white';
    }else{
        var strapColour = 'black';
    }

    var textBg = new Image();
    textBg.src = 'images/text-bg/'+colour+'-'+opacity+'-'+size+'-'+alignment+'.png';
    textBg.onload = function(){
    context.drawImage(textBg, 0, 0);
    }

    var strap = new Image();
    strap.src = 'images/straps/strap-'+strapColour+'-'+alignment+'-'+size+'.png';
    strap.onload = function(){
        context.drawImage(strap, 0, 0);
    }}

Upvotes: 2

Views: 1184

Answers (1)

Shahar Nacht
Shahar Nacht

Reputation: 122

Try this:

var BGloaded=false;
var logoloaded=false;

textBG.onload=function()
{
    BGloaded=true;
    tryToDraw();
}

strap.onload=function()
{
    logoloaded=true;
    tryToDraw();
}

function tryToDraw()
{
    if (BGloaded && logoloaded)
    {
        context.drawImage(textBg, 0, 0); //draw it first
        context.drawImage(strap, 0, 0); //and then draw that!
    }
}

Another option: (proposed by markE)

var loaded=0;

textBG.onload=function()
{
    loaded++; //does the same as loaded+=1
    tryToDraw();
}

strap.onload=function()
{
    loaded++;
    tryToDraw();
}

function tryToDraw()
{
    if (loaded==2) //the total amount of images
    {
        context.drawImage(textBg, 0, 0); //draw it first
        context.drawImage(strap, 0, 0); //and then draw that!
    }
}

I hope i could help! =)

Upvotes: 2

Related Questions