Spicy Yoghurt | Last updated: 2 Februari 2019 | HTML5 game
Draw a rectangle on the canvas
This tutorial requires the basic HTML5 file you have created in the previous tutorial. If you skipped that step, you can download the basic HTML5 file with canvas here.
The window.onload event will trigger once the whole page is loaded. This will make sure all elements and resources on the page are available. The init() function is set as the event handler. Once the onload event fires, init() will be called.
Inside the init() function, the canvas is stored for later reference by calling getElementById(). Once the references are made, the first drawing operation is performed.
This is what you get:
Draw on the canvasWhen you add the previous code to your index.html file, and run the file in the browser, you will actually see something getting draw on the canvas. It's a big rectangle!
By calling draw() in the init() function, a rectangle has been draw to the canvas. You can modify the params inside the function to create rectangles of different sizes and colors.
Draw with a random colorWith the current code, the rectangle is either red or blue. This is because every time the page is loaded a new random color is picked in the draw() function, by using Math.random() to pick a color. You can try to refresh this page a couple of times and see the color getting changed.
The random color is used to demonstrate the fact that you are not looking at a static image. You are drawing your own graphics!
Final codeYou can draw on the canvas now. The total code looks like this:
You can copy and store this code in a file, or download the complete file here. Feel free to ask questions in the comments.
Game development tutorial - Spicy Yoghurt
In the next step of the tutorial, you will learn how to do multiple drawing operations. You will create a game loop!