我正在尝试在我的 Canvas 中绘制第一个绿色坦克,但我认为我的代码中遗漏了一些东西
jsfiddle :
draw: function () {
tankImg.onload = function () {
ctx.drawImage(tankImg, this.Pos * this.w, 0, this.w, this.h, this.x, this.y, this.w, this.h);
};
}
谁能帮帮我?
最佳答案
好的,首先非常感谢 fiddle - 让一切变得简单十亿倍。
您的代码中有 两个 个错误 - 第一个是 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 的版本要好得多。
关于javascript - 在 html5 canvas 中绘制图像的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21623756/