Why can't I draw my rectangle

My code

I’m trying to get starting won’t making games different than the text games I’ve learned how to make. I forgot a lot of HTML while learning JavaScript so I went back and learned how to draw a rectangle and shapes to incorporate into my code for games. I want to make a basic snake game, so I am trying to draw this rectangle, but my code won’t work and I can’t figure out why.

Most of the time you want to put your script tags at the end of the body. When you put the script tag in the head and try to access an element in the document it will be undefined because the page has not loaded yet.

<!DOCTYPE html>
    <link rel='stylesheet' href='style.css'/>
    <canvas id = "canvas" width = "200" height "200">
    <script src='script.js'></script>

If you do put the script in the head you will need some sort of document onload event listener.


Thank you very much. It worked!

1 Like