我正在做一个简单的游戏(学习Zenva学院的教程),虽然我遵循了T的说明,但我似乎无法在浏览器中显示我的画布形状。下面是我到目前为止掌握的代码:
var canvas = document.getElementByID('myCanvas');
var ctx = canvas.getContext('2d');
let screenWidth = 1000;
let screenHeight = 500;
class GameCharacter {
constructor(x, y, width, height, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
}
var blueSquare = new GameCharacter(
50, 50, 50, 50, "rgb(0, 0, 255)"
);
var rectangle = new GameCharacter(
75, 75, 100, 50, "rgb(0, 255, 0)"
);
var redSquare = new GameCharacter(
100, 50, 50, 50, "rgb(255, 0, 0)"
);
var draw = function() {
ctx.clearRect(0, 0, screenWidth, screenHeight);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillRect(blueSquare.x, blueSquare.y, blueSquare.width, blueSquare.height);
ctx.fillStyle = rectangle.color;
ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = redSquare.color;
ctx.fillRect(redSquare.x, redSquare.y, redSquare.width, redSquare.height);
}
var step = function() {
draw();
window.requestAnimationFrame(step);
}canvas {
border: 4px solid green;
background-color: yellow;
}<canvas id='myCanvas' width='1000' height='500'></canvas>
我对此还很陌生,这是我在论坛上提出的第一个问题。如果我做错了什么请告诉我。LOL!
我正在使用的:
操作系统: Windows 10 Pro 64位
浏览器:尝试了Chrome和Microsoft
代码编辑器:崇高文本3
发布于 2020-03-15 16:24:49
一个简单的错误--您已经编写了getElementByID,而应该有getElementById。(这将立即显示在浏览器的开发工具控制台中。)
然后,您需要给step()打一次电话来启动它。
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
let screenWidth = 1000;
let screenHeight = 500;
class GameCharacter {
constructor(x, y, width, height, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
}
var blueSquare = new GameCharacter(
50, 50, 50, 50, "rgb(0, 0, 255)"
);
var rectangle = new GameCharacter(
75, 75, 100, 50, "rgb(0, 255, 0)"
);
var redSquare = new GameCharacter(
100, 50, 50, 50, "rgb(255, 0, 0)"
);
var draw = function() {
ctx.clearRect(0, 0, screenWidth, screenHeight);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillRect(blueSquare.x, blueSquare.y, blueSquare.width, blueSquare.height);
ctx.fillStyle = rectangle.color;
ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = redSquare.color;
ctx.fillRect(redSquare.x, redSquare.y, redSquare.width, redSquare.height);
}
var step = function() {
draw();
window.requestAnimationFrame(step);
}
step();canvas {
border: 4px solid green;
background-color: yellow;
}<canvas id='myCanvas' width='1000' height='500'></canvas>
https://stackoverflow.com/questions/60695004
复制相似问题