function render()
{
canvasBackground.drawImage(images[0], 0, canvas.height / 2, canvas.width, canvas.height / 2);
}
function initImages(paths)
{
requiredImages = paths.length;
for (i in paths)
{
var img = new Image();
img.src = paths[i];
images[i] = img;
images[i].onload = function ()
{
doneImages++;
}
}
}
function checkImages()
{
if (doneImages >= requiredImages)
{
loop();
}
else
{
setTimeout(function ()
{
checkImages();
}, 1);
}
}
initImages(["picture.png"]);
checkImages();
我确实做到了这一点但没有出现任何问题,任何想法如何解决这个问题?
顺便说一下,我没有向你展示循环函数,循环函数反过来运行渲染函数。
答案 0 :(得分:1)
以下是您的代码的重构版本。
它增加doneImages
,直到它等于paths.length
(此时所有图像都已完全加载)。
然后在每个图像索引上调用render
。
顺便说一下,你的渲染功能是通过拉伸它们来扭曲你的图像。我认为这是故意的吗?
示例代码和演示:
var canvas=document.getElementById("canvas");
var canvasBackground=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var images=[];
var paths=[];
paths.push('https://dl.dropboxusercontent.com/u/139992952/multple/animated.gif');
paths.push('https://dl.dropboxusercontent.com/u/139992952/multple/ball1.png');
initImages(paths);
function render(i)
{
canvasBackground.drawImage(images[i], 0, canvas.height / 2, canvas.width, canvas.height / 2);
}
function initImages(paths)
{
var doneImages=0;
for (i in paths)
{
var img = new Image();
img.src = paths[i];
images[i] = img;
images[i].onload = function ()
{
// just return if all the images aren't loaded yet
if(++doneImages<paths.length){return;}
for(var i=0;i<images.length;i++){ render(i); }
}
}
}
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;