Draw multiple images on canvas / preload images

I’m trying to draw 2 images pulled from 2 select tags on my page with the following code:

<select id="badge1" class="badges" onchange="ReDraw()">
<option value="0001">1</option>
<option value="0002">2</option>
<option value="0003">3</option>
</select>
<select id="badge2" class="badges" onchange="ReDraw()">
<option value="0001">1</option>
<option value="0002">2</option>
<option value="0003">3</option>
</select>
let badge1Select = document.getElementById("badge1");
let badge2Select = document.getElementById("badge2");

Within my ReDraw():

let img2 = new Image();
img2.onload = () => {
 ctx.drawImage(img2, 175 - img2.width / 2, renderGroup[0][1] - img2.height -5);
};
let img1 = new Image();
img1.onload = () => {
 ctx.drawImage(img1, 175 - img1.width / 2, renderGroup[0][1] - img2.height -5 - img1.height);
};
img2.src = `Badges/${badge2Select.value}.png`;
img1.src = `Badges/${badge1Select.value}.png`;

The renderGroup[0][1] is just a dynamic Y-Coordinate that changes based on something else in my code. That part works fine.

My intention with this is that when 2 badges are selected, i’d like:

  • badge2 to be drawn above renderGroup[0][1] with 5 pixels of buffer space.
  • badge1 to be drawn above badge2 with 5 pixels of buffer space.

My problem:
Is that when I run this code and select 2 badges, the badges are drawn on top of each other not as intended. However if I cycle back and forth on the select, they will be drawn properly above each other as intended. It’s so weird it’s like the first time I call an image, it does’t draw properly but cycling back and forth does…

I added a little console log to find out why the height is giving me issues:

console.log(img2.height);
console.log(img1.height);

Console:

app.js:217 0
app.js:218 66

I hope I put all the information clearly and as concise as I possibly could. I know it has something to do with preloading images I just can’t quite figure it out. I know the answer to this would be trivial to some but I’ve wasted an embarrassing amount of time trying to figure it out I’m turning to you guys.

Thanks

78 thoughts on “Draw multiple images on canvas / preload images”