[HowTo] HTML5 Game tutorial Part 2 | The first contact

in #html5game6 years ago

Hidideli ho everyone, 

I have a good day and don't need to go get to work so early so i will write the second part of the tutorial right after the first one :)

So what did we do last time. We installed a http server for testing our game and set up a project folder and the index.html inside of the folder. So what we do now is to create a canvas object in the index.html and show a little message on the screen.

To draw things on the screen we need a canvas object. On the first 3 line we specifiy the height and the width of the object and create the element with the given height.

On the fourth line we tell js to append those code to the body tag of the html file. When we now fire up a browser window and head to localhost/game we will see...

...nothing. Because we did not paint anything to the screen.

To do that we need to create a game loop. The main loop is looking like this:

Now our main.js should look like this.
The setInterval function will run the methods draw() and update() every 33 milliseconds which means that we get a frame rate of about 30 FPS.
At the draw function we tell the canvas element to draw the text "Hello Canvas at the position (125|125).
As normal in 2D games the position coordinates are meant from the top left corner of the screen, in this case from the canvas element.

So if we now refresh the browser we will see again nothing, because we need to add a last tag on the index.html.

We need to add this tag after the body-tag. If we dont do it the script will not find the body-tag and you will see again nothing then a white screen.

But now. If you now hit Ctrl+R you will see our nice "Hello Canvas"-message at the given coordinates.

Very nice our first web-app. So let us make a short

Conclusion

  1. What did we learn? We made a skeleton of html tags to show our drawings on the index.html
  2. We created a javascript file which contains our game code and added it at the bottom of the html file
  3. We told the setInterval function to run our draw() and update() funcdtion every 33 ms to get nearly 30 FPS
  4. We implemented the draw() and update() function and told the draw function to draw our message at the given coords
  5. We looked at our result on the browser and get a slightly smile

So i think thats all for today. Feel free to play around with our code and write some other lines on the screen. And the most importent thing

Stay tuned and interested folks. Read us later

Coin Marketplace

STEEM 0.25
TRX 0.20
JST 0.038
BTC 95773.12
ETH 3595.18
USDT 1.00
SBD 3.80