Javascript Canvas图像并不总是加载

时间:2018-07-11 05:04:51

标签: javascript loops for-loop if-statement canvas

有时,我第一次访问页面时会加载图像,而有时我必须刷新才能加载它们。有时一幅图像也会加载,而另一幅图像不会加载。

//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));
    }
}

我还尝试了以下相同的结果:

//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>

我只是不知道使用div类将div标签中的每个图像加载到canvas上的正确方法。

1 个答案:

答案 0 :(得分:1)

您可能要考虑使用window.onload。此回调仅在页面上的所有图像加载完成后才会触发,因此此时处理图像可能会更成功。这是stack overflow post,其中包含更多信息以及the documentation for window.onload

您将采用以下结构:

window.onload = function() {
    dimgs.forEach(function(img) {
        getcan(img);
    });
}