Javascript Canvas images don't always load
本问题已经有最佳答案,请猛点这里访问。
有时我的图像在我第一次访问页面时加载,有时我必须刷新它们才能加载。 有时也会加载一个图像而不加载另一个图像。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //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)); } } |
我也尝试了以下相同的结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //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:
1 2 3 4 5 6 7 8 9 10 | <canvas id="hairimg" style="border: 1px solid #000;"></canvas> <canvas id="headimg" style="border: 1px solid #000;"></canvas> <img src="hair.png" alt="User Image"> <img src="head.png" alt="User Image"> |
我只是不知道使用
您可能需要考虑使用window.onload。 只有在页面上的所有图像都加载完毕后才会触发此回调,因此在此时处理图像可能会更成功。 这是一个包含更多信息的堆栈溢出帖子,以及window.onload的文档。
你的结构是这样的:
1 2 3 4 5 | window.onload = function() { dimgs.forEach(function(img) { getcan(img); }); } |