1

我正在尝试创建一个用于画布游戏的简单 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//
4

1 回答 1

0

更正:

  • image.onload 函数定义上没有引号
  • image.onload 函数定义上没有括号
  • image.onerror 需要函数定义或匿名函数
  • 将 image.onerror 放在 image.src 之前

这是一些示例代码:

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
}
于 2013-09-20T05:21:09.980 回答