画布drawimage循环超时



我正在尝试用canvas对象编写一个小型流式客户端。

这是必要的代码:

this.drawPictures = function() {
var i = 0;
while (i <= 3000) {
this.addPicture("Pictures/Wildlife/" + i + '.bmp', 1, 1);
i = i + 4;
}
}

这很好用!图像将显示出来。但这不是我想要的。

我想设置FPS限制。所以我需要在这个循环中有1000毫秒/帧的"睡眠"。

我已经尝试了一些使用SetInterval或SetTimeOut的方法。但他们都不适合我。

所以我试着写我自己的睡眠:

var i = 0;
timeStart = new Date().getTime();
while (i <= 3000) {
timeNow = new Date().getTime();
timeDifference = timeNow - timeStart;
if (timeDifference > 1000*i) {
this.addPicture("Pictures/Wildlife/" + i + '.bmp', 1, 1);
i = i + 1;
}
}

我在循环之前保存了实际的Datetime,当时差达到1000ms时,我正试图加载一张图片并增加I。

我的问题:当我用alert(I)而不是this.addPicture这样做时,效果很好!我每1000ms(每秒)收到一个警报

当我像上面的例子一样(使用this.addPicture)时,浏览器只是在加载自己,直到我收到无法加载页面的错误。但是我没有看到任何照片!

这是我的addPicture函数:

this.addPicture = function (cPicPath, nSizeX, nSizeY) {
var imageObj = new Image();
imageObj.onload = function () {
ctx.drawImage(imageObj, nSizeX, nSizeY);
}
imageObj.src = cPicPath;
}

有人知道为什么它能用alert而不能用addPicture吗?因为当我不使用时间戳(第一个代码示例)时,它工作得很好!

在ctx.drawImage中,imageObj后面的两个参数是X/Y,而不是图像大小。

您需要给足够的时间来加载图像(1秒的时间不够)。

您的addPicture开始(但未完成)加载图像,但在再次调用addPicture时图像尚未完全加载。

有很多图像加载程序。。。这里有一个:

var imageURLs=[];  // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("myPicture1.png");
imageURLs.push("myPicture2.png");
imageURLs.push("myPicture3.png");
imageURLs.push("myPicture4.png");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){ 
imagesOK++; 
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");} 
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}      
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// Start your timer and display your pictures with addPicture
}

最新更新