Javascript Image()无法加载或绘制

时间:2013-09-20 01:22:30

标签: javascript html5 image canvas onload

我正在尝试创建一个用于画布游戏的简单Sprite类,但是我在创建类的新实例时指定的图像从不调用onload或onerror。 发生了什么,如何让它加载并绘制图像?

这是脚本:

var cvs = document.getElementById("c");
var ctx = cvs.getContext("2d");
var imagesToLoad = 1 ;
var imagesLoaded = 0;
var gameState = 0;
//START OF IMAGE STUFF//
function imageOnload() {
    imagesLoaded+=1;
    console.log("Images: loaded "+imagesLoaded+" overall.");
}
function loadLoop() {
    if (imagesLoaded == imagesToLoad) {
        gameState = 1;
    }
}
function loop1() {
    ctx.drawImage(circle.image);
}
function gameLoop() {
    if(gameState==0){
        loadLoop();
    }
    if(gameState==1){
        loop1();
    }
}

function Sprite(positionsArray){
    this.x = positionsArray[0];
    this.y = positionsArray[1];
    this.dx = positionsArray[2];
    this.dy = positionsArray[3];
    this.angle = positionsArray[4];
    this.rotating = positionsArray[5];


};
circle = new Sprite(new Array(0, 0, 0, 0, 0, 0));
circle.image = new Image().onload="imageOnload()".src="circle.png".onerror="console.log(\"Nope.\")";
console.log("circle?");
setInterval(function(){gameLoop()}, 10);
//END OF IMAGE STUFF//

1 个答案:

答案 0 :(得分:0)

更正:

  • image.onload函数定义没有引号
  • image.onload function definition
  • 上没有任何内容
  • image.onerror需要函数定义或匿名函数
  • 在image.src
  • 之前放置image.onerror

以下是一些示例代码:

circle.image=new Image();
circle.image.onload=imageOnLoad;
circle.image.onerror=function(){console.log("Image failed to load")};
circle.image.src="koolaidman.png";

function imageOnLoad(){
    ctx.drawImage(circle.image,0,0);  // or do other stuff
}