redliz5808 :
I am working on a simple game (following a tutorial on Zenva Academy) and, although I've followed the instructions to a T, I can't seem to get my canvas shapes to show up in the browser. Here is the code I have so far:
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>
I am still fairly new to this and this is the first question I've ever asked on a forum. Let me know if I'm doing something wrong. LOL!
I am using:
OS: Windows 10 Pro 64-bit
Browser: Tried both Chrome and Microsoft Edge
Code Editor: Sublime Text 3
AKX :
A simple typo - you have written getElementByID
, while you should have getElementById
. (This shows up immediately in your browser's developer tools' console.)
Then, you'll need to call step()
once to kick things off.
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>
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=342240&siteId=1