图像数组不会绘制到画布

时间:2015-06-04 01:34:53

标签: javascript canvas setinterval

我正在学习JavaScript。如果有人能解释我在哪里犯了错误,那就太好了。

我有一个带有图片链接的数组并将它们放入函数中,该函数应该在画布上为每个带链接的图片绘制图像。

function draw(imgs){

    var step = 0;  // I want to start with zero;

    imgs.forEach(function(src){   // then go through the array links

    // and I want to draw the images from the array

    con.drawImage(src, 0, step, 200 , 150)

        step += 20;  // This is the step for the next picture

    console.log(step)
    console.log(src)
    })

    console.log(imgs);
}

然后执行:

window.onload = function(){
    setInterval(function(){
      loadImg(arr, draw)    
    }, 1000)
...

它显示了我的阵列的第一张照片以及setInterval最后一张照片。

抱歉描述不好,现在是早上5点

P.S。

loadImage是创建具有少量src图像的数组的函数:

function loadImg(linkArr, draw){
    var imgs = [];

        linkArr.forEach(function(link){
            var img = new Image();

            img.src = link
            imgs.push(img);


        })
            draw(imgs)

    };

1 个答案:

答案 0 :(得分:1)

很难准确说出你在哪里犯了错误。看起来所有图像都是在第一次调用loadImg的同时添加的。为了让您的示例延迟绘制图像,您需要延迟将实际源添加到阵列,因此每个间隔只发送1个URL。

由于这是您学习的一个例子,我不会探讨如何优化它。

请参阅下面的代码,这是您要完成的工作示例。看到评论,希望你会看到发生了什么。

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
c.width = 400;
c.height = 400;
var images = [];
var links = ["http://pattersonrivervet.com.au/sites/default/files/pictures/Puppy-10-icon.png",
           "https://38.media.tumblr.com/avatar_2be52b9ba912_128.png"];
var counter = 0;

function draw(imgs){
    ctx.clearRect(0,0,c.width,c.height);
    var step = 0;  // I want to start with zero;
    imgs.forEach(function(src){   // then go through the array links
        // and I want to draw the images from the array
        ctx.drawImage(src, 0, step);
        step += src.height;  // This is the step for the next picture. Let's use the height of the image.
    })
}

function loadImg(link){
    var img = new Image();
    img.src = link;
    images.push(img);
    draw(images);
};


var myInterval = setInterval(function(){ //I set the interval to a variable so that I can remove it later if needed.
    // you can add images in different ways, I used an array of links
    loadImg(links[counter]);
    
    counter++; //set counter to next image
    if (counter > links.length) {
        //if we're out of images, stop trying to add more
        clearInterval(myInterval); 
    }     
}, 3000);
ctx.fillText("pictures appear in 3s intervals",10,10);
<canvas id="canvas"></canvas>

相关问题