图像数组不能绘制到画布上

Image array won't draw to canvas

本文关键字:绘制 数组 不能 图像      更新时间:2023-09-26

我正在学习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点

公立小学

loadImage是一个函数,用于创建一个包含少量图像src的数组:

function loadImg(linkArr, draw){
    var imgs = [];
        linkArr.forEach(function(link){
            var img = new Image();
            img.src = link
            imgs.push(img);

        })
            draw(imgs)
    };

很难说你到底在哪里犯了错。似乎所有的图像都是在第一次调用loadmg时同时添加的。为了让您的示例以延迟方式绘制图像,您需要在将实际源添加到数组时设置延迟,因此每个间隔只发送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>