javascript drawImage()问题

时间:2014-03-15 18:13:39

标签: javascript html5 canvas

目前drawImage();存在一些问题。即它实际上不会画画。我使用fillRect();进行了尝试,并将drawImage();置于onload函数内部(以及有效)。

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 400;
document.body.appendChild(canvas);

var tileArray = [
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,1,0,0,1,0,0,0],
[0,0,0,1,1,1,1,0,1,1,1,0,0],
[0,0,0,1,1,1,0,0,0,0,1,1,0],
[0,0,0,1,1,1,0,0,0,0,0,0,0],
[0,0,0,1,1,1,0,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0,0,0],
[0,0,0,0,0,1,1,1,0,0,0,0,0],
[0,0,0,0,0,0,1,1,0,0,0,0,0]
];

var grassReady = false;
var grass = new Image();
grass.onload = function() {
        grassReady = true;
};
grass.src = "images/grass.png";

var sandReady = false;
var sand = new Image();
sand.onload = function() {
    sandReady = true;
};
sand.src = "images/sand.png";

var posX = 0;
var posY = 0;

if(grassReady) {
    ctx.drawImage(grass, posX, posY);
}

任何关于为什么会这样做的指针都会非常感激,如果搞砸了代码部分,我会提前道歉。我经历了其他类似的帖子,并且找不到似乎有用的解决方案。

2 个答案:

答案 0 :(得分:0)

此声明ctx.drawImage();应位于grass.onload = function() {}函数内,类似

grass.onload = function() {
     ctx.drawImage(grass, posX, posY);
}

如果您在drawImage()函数之外定义grass.onload(),那么该状态将首先执行,因此此时grassReady为false,因此不满足条件。

基本上它与异步概念有关。

您的代码正在按顺序运行

1)首先

var grassReady = false;

if(grassReady) {
    //grassReady is false, this condition is not satisfied
    ctx.drawImage(grass, posX, posY);
}

2)第二次

grass.onload = function() {
     grassReady = true;
};

答案 1 :(得分:0)

正如@Suman Bogati所说,你必须等待你的图像加载才能在drawImage中使用它们。

演示:http://jsfiddle.net/m1erickson/jGPGj/

enter image description here

这是一个图像加载器,可以预加载所有图像,然后调用start()函数,您可以使用drawImage,因为所有图像都已完全加载。

var imageURLs=[];  // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("images/grass.png");
imageURLs.push("images/sand.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[]

    // grass.png is in imgs[0]
    // sand.png is in imgs[1]

}