【问题标题】:canvas drawimage loop with timeouts带有超时的画布drawimage循环
【发布时间】:2014-01-11 12:37:25
【问题描述】:

我正在尝试使用画布对象编写一个小的流式客户端。

这是必要的代码:

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

我在循环之前保存实际的日期时间,并且恰好在时差达到 1000 毫秒时,我正在尝试加载图片并增加 i。

我的问题: 当我使用 alert(i) 而不是 this.addPicture 执行此操作时,它可以正常工作!我每 1000 毫秒(每秒)收到一次警报

当我像上面的示例(使用 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 吗?因为当我不使用时间戳(第一个代码示例)时,它可以正常工作!

【问题讨论】:

    标签: javascript loops canvas stream


    【解决方案1】:

    在您的 ctx.drawImage 中,imageObj 之后的 2 个参数是 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
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      • 2016-05-16
      • 2012-11-30
      • 2011-10-27
      • 2020-06-08
      • 2013-12-22
      • 2015-03-02
      相关资源
      最近更新 更多