为什么我的图像不能立即绘制? HTML5画布

时间:2014-06-24 16:45:25

标签: arrays html5 image loops canvas

所以,这是我的代码

function drawLocations(){
    var i = 2;
    var storedData = sessionStorage.locations;
    locations = JSON.parse(storedData);
    while(i<25){
        var img = new Image();
        img.src = locations[i];
        ctx.drawImage(img,i*20,canvas.height-40);
    i++;
    }
}

当我在控制台中打印sessionStorage.locations变量时,它会打印一个看起来像这样的数组......

["","","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png","spike.png"]

这正是应该做的。我用JSON对数组进行了字符串化,因此在sessionStorage中存储数组不是问题。问题是,当我运行我的代码时,需要大约30秒来绘制屏幕上的所有尖峰。我不知道是怎么回事。

1 个答案:

答案 0 :(得分:2)

在尝试绘制图像之前,你没有给你的图像加载时间。

您必须使用.onload,它会在您的图像完全加载后调用。

以下是使用image.onload:http://jsfiddle.net/m1erickson/yjS2L/

的示例

enter image description here

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/picketFence.jpg";
function start(){
    for(var i=0;i<3;i++){
        ctx.drawImage(img,i*99,canvas.height-img.height);
    }
}