Sometimes my images load the first time I visit the page and other times I have to refresh for them to load. Also sometimes one image will load and not the other.
//Store everything in arrays
var dimgs = ["hair-1", "head-1"]; //Name of classes for imgs
var cans = ["hairimg", "headimg"]; //Canvas element names
var dcans = ["chairimg", "cheadimg"]; //Canvas names
var dctxs = ["ctxa", "ctxb"]; //Context names
var defimgs = []; //Images found
//Loop to create Canvas and draw image
for (var p = 0; p < 2; p++) {
if(p != null) {
getcan(p);
}
}
//Function to create Canvas and draw image
function getcan(p) {
defimgs[p] = document.getElementsByClassName(dimgs[p])[0].getElementsByTagName('img')[0];
var x;
if(p != null) {
defimgs[p].onload = (function(x){
dcans[x] = document.getElementById(cans[x]);
dctxs[x] = dcans[x].getContext('2d');
dcans[x].width = defimgs[x].naturalWidth;
dcans[x].height = defimgs[x].naturalHeight;
dctxs[x].drawImage(defimgs[x], 0, 0);
}(p));
}
}
I've also tried the following with the same results:
//Store everything in arrays
var dimgs = ["hair-1", "head-1"]; //Name of classes for imgs
var cans = ["hairimg", "headimg"]; //Canvas element names
var dcans = ["chairimg", "cheadimg"]; //Canvas names
var dctxs = ["ctxa", "ctxb"]; //Context names
var defimgs = []; //Images found
//Loop to create Canvas and draw image
for (var p = 0; p < 2; p++) {
if(p != null) {
defimgs[p] = document.getElementsByClassName(dimgs[p])[0].getElementsByTagName('img')[0];
dcans[p] = document.getElementById(cans[p]);
dctxs[p] = dcans[p].getContext('2d');
dcans[p].width = defimgs[p].naturalWidth;
dcans[p].height = defimgs[p].naturalHeight;
getcan(p);
}
}
//Function to draw image
function getcan(p) {
var x;
if(p != null) {
defimgs[p].onload = (function(x){
dctxs[x].drawImage(defimgs[x], 0, 0);
}(p));
}
}
HTML:
<div>
<canvas id="hairimg" style="border: 1px solid #000;"></canvas>
</div>
<div>
<canvas id="headimg" style="border: 1px solid #000;"></canvas>
</div>
<div class="hair-1"">
<img src="hair.png" alt="User Image">
</div>
<div class="head-1"">
<img src="head.png" alt="User Image">
</div>
I just don't know the proper way to load multiple images that are each in a div
tag using the div
class onto a canvas
.