【发布时间】:2017-08-26 13:40:21
【问题描述】:
这是我用于矩形船的 JS 画布代码。如果我注释掉 switch 语句,船是可见的。在取消注释 switch 语句时,船没有显示。怎么了?
var ship = function() {
this.velocityX = 0;
this.velocityY = 0;
this.accelerationX = 0;
this.accelerationY = 0;
this.x = width / 2;
this.y = height / 2;
this.speed = 4;
this.angle = 0;
this.control = function() {
context.save();
context.translate(this.x, this.y);
this.addEventListener("keydown", function(event) {
switch (event.keyCode) {
case 36:
this.accelerationX = Math.cos(this.angle) * this.speed;
this.accelerationY = Math.sin(this.angle) * this.speed;
break;
case 38:
this.accelerationX = -Math.cos(this.angle) * this.speed;
this.accelerationY = -Math.sin(this.angle) * this.speed;
break;
case 37:
this.angle -= 0.5;
break;
case 40:
this.angle += 0.5;
break;
}
});
context.rotate(this.angle);
context.fillStyle = "rgb(255,255,255)";
context.fillRect(0, 0, 20, 30);
context.restore();
};
};
【问题讨论】:
-
JSHint 只检测语法错误,不会检测任何运行时错误。
-
无论如何你确定你的变量、角度、x 和 y 已经定义了吗? this.angle != 角度
-
好的,我将其更改为 context.rotate(this.angle) 并且取消注释该行现在不会导致问题。也改变了 x 和 y。
-
好吧,我只是错过了一堆这个关键字。我更新一下代码,好像还是有问题。
-
在我看来,您似乎需要更好地理解关键字
this。
标签: javascript html html5-canvas translate-animation