JavaScript画布白色屏幕

时间:2017-04-02 05:26:13

标签: javascript html html5 canvas

我现在真的很沮丧,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();
}; 

1 个答案:

答案 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;
}