gpt4 book ai didi

JavaScript Canvas 白屏

转载 作者:行者123 更新时间:2023-12-01 03:51:18 25 4
gpt4 key购买 nike

我现在真的很沮丧,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.innerWidth/insideHeight 不是方法/函数,它是 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>

关于JavaScript Canvas 白屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com