Reputation: 13
I'm brand new to both coding and this site, and I've run into a problem that actually wasn't a problem before.
I'm following along with a video to code Tetris in Javascript, and at first I was using p5.js editor to do my coding, but found that I was running into a lot of issues, syntax not matching up, etc.
I've moved to Atom editor as it seems to have similar functionality as the video - and please keep in mind, I'm an absolute beginner, following along is the best I can do.
So, here's the code. The problem is that it's supposed to create a 240x400 canvas, and in p5.js it does, but everywhere else, it doesn't. I've tried first using Node.js to get a preview of the code, and that turned up blank. Now I'm using a live HTML preview package in Atom, which also turns up blank.
<html>
<head>
<title>Tetris</title>
</head>
<body>
<canvas id="tetris" width="240" height="400"></canvas>
<script src="tetris.js"></script>
</body>
</html>
The Javascript source it references is below.
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
I've got no clue how to fix this, and I'm not sure posting here will be of any use at all, but I've been tearing my hair out trying to get this to work in an editor that can simply let me follow along, and it sadly doesn't want to cooperate.
Thanks in advance for any help you can provide!
Upvotes: 1
Views: 303
Reputation: 318
document.addEventListener("DOMContentLoaded", function () {
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
})
You have written well, It will create black box, hope this work for you.
Upvotes: 0
Reputation: 756
Your code is correct. You could try waiting with your drawing until the page is fully loaded:
document.addEventListener("DOMContentLoaded", function () {
const canvas = ...
...
});
Upvotes: 1