好的,首先非常感谢小提琴 - 让一切变得简单十亿倍。
您的代码中有两个三个错误 - 第一个是 tankImg.onload 函数。 onload 函数只触发一次 - 当图像首次加载时。
你想要的是 tankImg.complete,如果加载则返回 true,否则返回 false。
其次,您不能为 y 属性分配“ch - this.h”,因为直到您完成定义后才定义“this”。您可以做的是在您的绘图代码中设置 y 值。
第三,在 javascript 中你不能做 var cw, ch = 400;
$(document).ready(function () {
var cw = 400;
var ch = 400;
var ctx = $("#MyCanvas")[0].getContext("2d");
var tankImg = new Image();
tankImg.src = "http://oi62.tinypic.com/148yf7.jpg";
var Fps = 60;
var PlayerTank = {
x: cw / 2,
w: 84,
h: 84,
Pos: 2,
draw: function () {
ctx.drawImage(tankImg, this.Pos * this.w, 0, this.w, this.h, this.x, ch - this.h, this.w, this.h);
}
};
var game = setInterval(function () {
if (tankImg.complete) {
PlayerTank.draw();
PlayerTank.x++;
}
}, 1000 / Fps);
});
这里是完整的jsfiddle,带有额外的乐趣。
编辑:Ken 处理 .onload 的版本要好得多。