我现在真的很沮丧,JS从不为我工作。我不知道这次我犯了什么小错误,如果你指出它,我将不胜感激。我不想要动画或任何东西,如果有人告诉我错误,我会很高兴。
window.onload = function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth();
canvas.height = window.innerHeight();
var ship = function() {
this.x = canvas.width/2;
this.y = canvas.height/2;
this.velocityX = 0;
this.velocityY = 0;
this.accelerationX = 0;
this.accelerationY = 0;
this.show = function() {
//background
context.fillStyle = 'rgb(0,0,0)';
context.fillRect(0,0,canvas.width,canvas.height);
//update
this.velocityX += this.accelerationX;
this.velocityY += this.accelerationY;
this.x += this.velocityX;
this.y += this.velocityY;
//draw
context.save();
context.translate(this.x,this.y) ;
context.fillStyle = 'rgb(0,0,0)';
context.fillRect(0,0,20,30);
context.restore();
};
};
var myship = new ship();
myship.show();
};
答案 0 :(得分:2)
你有两个问题......
1。 innerWidth / innerHeight
不是方法/函数,它是window
对象的属性。所以,正确的形式是window.innerWidth / window.innerHeight
2。您无法查看ship
对象,因为您同时设置背景和发货 { {1}} 黑色。因此,要么将背景的fillStyle
或发货更改为其他颜色。
fillStyle
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ship = function() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.velocityX = 0;
this.velocityY = 0;
this.accelerationX = 0;
this.accelerationY = 0;
this.show = function() {
//background
context.fillStyle = 'rgb(255,255,255)';
context.fillRect(0, 0, canvas.width, canvas.height);
//update
this.velocityX += this.accelerationX;
this.velocityY += this.accelerationY;
this.x += this.velocityX;
this.y += this.velocityY;
//draw ship
context.save();
context.translate(this.x, this.y);
context.fillStyle = 'rgb(0,0,0)';
context.fillRect(0, 0, 20, 30);
context.restore();
};
};
var myship = new ship();
myship.show();
#canvas {
border: 1px solid black;
}