JavaScript Canvas白色屏幕
问题描述:
我真的很沮丧,JS从来没有为我工作。我不知道这次我犯了什么小错,如果你指出,我会很感激。我不想动画或任何东西,如果有人告诉我错误,我会很高兴。JavaScript Canvas白色屏幕
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();
};
答
你有两个问题...
innerWidth/innerHeight
不是一个方法/函数,它的window
对象的属性。所以,正确的形式是window.innerWidth/window.innerHeight
2.你是不是能够查看ship
对象,同时设置了背景的和船舶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;
}
<canvas id="canvas" width="300" height="300"></canvas>
是什么颜色的屏幕上的'canvas'? –
我这样做是因为我既不能查看黑色矩形也不能查看黑色对象,我得到一个白色屏幕 – udbhavs
不,我也试过JSHint。我在codepen上这样做。 – udbhavs