JavaScript HTML Game Development Tutorial 1 - Javascript Game Tutorial (Canvas)

JavaScript HTML Game Development Tutorial 1 – Javascript Game Tutorial (Canvas)

Views:143694|Rating:4.66|View Time:27:54Minutes|Likes:1104|Dislikes:81
2 years passed and the game engine developed here became Mosaic.js:

Javascript game tutorial part 1 | Canvas game tutorial | For beginners | JavaScript game engine tutorial | JavaScript game programming tutorial | javascript game coding | javascript game making | javascript game dev | javascript making a game | how to javascript a game | javascript tutorial for beginners with examples | create javascript game | javascript html game development tutorial 1 | making javascript games | how to make games with javascript

Welcome to the first JavaScript game development tutorial (HTML5 js canvas) for beginners! In this JavaScript game engine tutorial I will demonstrate one way of initializing canvas in JavaScript from scratch, which is the first step before we actually start drawing sprites and 2D tile worlds and making our own game engine.

[Russian/на русском языке] Как сделать игру на JavaScript? Этот урок программирования объяснит создание игры на JavaScript с нуля. Спрайт, анимация главного героя, РПГ, платформер движёк и графика и всё иное будет в этом туториал е объяснятся.

To start drawing game objects on the screen such as sprites, lines, rectangles and animations we first need to set up the canvas tag. This tutorial starts with a brief example of an HTML5 game made in canvas. And then in my next JavaScript game tutorial for beginners we’ll discover how to draw tiles and sprites.

Then it proceeds to minimum HTML and JavaScript coding required to draw to canvas. And no, we won’t be using enchant js here. Using rect method, the background is erased (cleared) to black color, concluding this canvas tutorial. The next tutorial will cover drawing 2d sprites on the canvas.

In a way, this is the very first step to developing a full fledged game engine in JavaScript. I’ll cover a few other subjects along the way that will prepare you for the future 😛

Support creation of my next tutorial on Patreon 🙂

For my gamedev news and updates please visit:

hey guys this is an example of JavaScript a canvas based game and it's something I've been working on for about four weeks and this is what I have in this tutorial I'm going to use all of what I learned about making games with canvas and this is going to be a very simple tutorial that demonstrates how to set up the canvas we're not going to go into details of actually making a game like this but eventually as we progress toward the next tutorial the next tutorial I'm going to show you how to draw sprites how to draw minds how to capture input for your game character and things like that so this is just a preview of what's possible with canvas so maybe hopefully somebody will find it inspiring and I'm basically including here because I wanted to give someone some hope I wanted to show you guys that if you take this seriously that at least you know because if I could do this then someone else could could do a very similar game or even better and if if I show it to set up canvas how to draw all these things how to draw the world how to animate characters maybe someone will actually learn to to make html5 games so I'm going to start the tutorial now so I'm going to switch off the game and I'm going to start with really basic stuff so let's get started this is tutorial number one hey guys this is the first tutorial in which I'm going to start a new series and we're going to start making video games with JavaScript and html5 I chose this medium in particular rather than installing C++ or Java IDE on your desktop computer because it's so much easier to just log in into jsfiddle net and it's such a great way to teach these concepts and show the result right away by just going to that link you'll see the source code that you can copy and paste and basically actually see the game working so I'm going to start by creating the canvas tag I'm going to go into HTML view on jsfiddle and it's a new tag in html5 it's called canvas and I usually give it an ID canvas the same thing canvas and just for simplicity's sake I'm going to add some style to it but the way you can vez operates is it basically has two width and height properties and it's really confusing sometimes when you just start it out because putting different values into these different parameters will kind of stretch the sprites and they will no longer be pixel perfect you will see some blurriness they will become a little blurry if you mismatch these parameters so oh let's create a canvas with width let's say maybe 640 high for a it's a really old resolution for old games back in the old days where we had 240 by 480 by 240 and stuff like that so here we define a canvas let's run this example and nothing is going to appear yet so let's add some style to it let's add a border so we can visually see it on the screen let's see here it appeared right here so this is 640 by 480 and the interesting thing you can add with 640 here again height and that's what I was talking about if you change these this six foot in this 480 or these ones the sprites will start to finish stretch and they will no longer be you know 1 to 1 ratio but that can be only demonstrated visually so I'm just going to leave this like this we matched 640 and 640 here this width and height can have different effects that's part of what I'm trying to explain now if you change 640 to something that's not 640 here again it's going to create some sprite stretching effect and I'll demonstrate that later on but so we created canvas and now we need to go into JavaScript I'm going to go into jsfiddle and add jQuery 111 an older version it doesn't really matter and I'm going to start writing my first JavaScript code as usual as you know you don't have to use jQuery to make games in html5 but it's definitely going to help you so document.ready function this is basically telling us that once all HTML elements have finished loading from that point we start writing our code so usually it's initialized initialization initialize sprites load pictures and stuff like that so we have this really nice canvas here but we don't really have a way to access anything on it it's just a HTML tag so in order to do this we need to know a little about Java scripts object and I could have created a context object using basic JavaScript functions but I'm going to go one step farther and create a custom context object that I can use later on this will allow me to add my own custom functionality to to that context object so basically I'm going to create my own constructor and call it context and that can be done like this so this is a new variable context and we're going to start adding things to it this canvas so we're adding a property canvas till the self-made object called context and another one is going to need context itself this is going to be the actual object html5 object context that refers to the canvas canvas has a context and we need to enable it before we can start drawing anything on it and in order to do that we need to create it first and we'll see how that can be done with you by using the get con text function in html5 but for now let's set it to null so this canvas context object will need a function create we can do it like actually I made a really bad mistake here hey guys it seems like I just made a mistake in the way I was explaining something and every time that's going to happen my tutorials I decided to use that as an opportunity to explain what that mistake was and what's going on here this will definitely help to understand JavaScript better and you know I will learn from my mistakes as well instead of just saying I made a mistake going to the next subject I don't think that anyone would learn anything from that and so every time I make a mistake all I'm going to create this intermission on a black background and that's how you would know that it's not part of the main tutorial but it's sort of like an intermission so anyway this mistake I just made I mixed up the function constructors with JavaScript object created Jason using Jason notation and here's the difference let's create object one this is jason notation and basically you can start adding variables to it or properties for example callers one and size 115 just for example and so this is a JSON object it's correctly formatted it already it's ready to start using in your project for example object 1 colors you can start out putting this into console.log or or alert object one colors or size so when you create an object using adjacent notation which is these brackets and then you just keep adding properties or functions using a comma for example draw it's a function you can see we can mix properties that are just values and functions inside the same object and here the base keyword will refer to colors or size in other words which refer to its own scope example colors will refer to colors value here or this size will refer to this parameter here size 150 inside this function so the mistake that I made I I started thinking that I'm creating a an object of type function which is a constructor so here you don't have to don't have to initialize JSON object to the plain JavaScript object you basically already created it you gave it a name these are all the properties that are stored and attached to it so you can start using it another type of an object is a function object object to assigned as a function it can be used in a very similar way but here we have to use the this keyword to define colors to for example this size 115 equal making the same mistake again equal so this object is really very similar to this object and you can even add a draw function which would be something like this and the difference between these two is that this is not a an initialized object yet when you create an object using the function keyword and as you know in JavaScript all functions are objects so that's the link when you create a function you really create an object as well just not represent it using JSON notation but it functions in the same exact way but in order for for that to happen we need to first initialize it so if we started calling object to callers this would produce an error because and this would actually return undefined but why is it returning undefined here when we create an object using jason we could have used it right away and it worked perfectly this this would be one should be 115 but here it would return undefined and the reason for that is because because this is a constructor object in order to start using it we first need to initialize it create an instance of that object so by itself this is more like a blueprint for that object at this point we can't use it in order to initialize it we go new object to like this so this initializes that object and creates an instance of the subject and here instead of going directly to the constructor now we can exit through the instance name that we just created here and this will return to now that it's initialized and sides will return 150 and so on so that's the mistake I was making is that I started making an object Oh using Jason because I just wanted to exist right away with so we don't have to initialize it that would make things a little simpler for the canvas example but I started assigning its properties using that this keyword like that and that just it doesn't work it's going to create a error because these are fundamentally two different ways of adding properties Jason uses the JSON format the comma and Colin the function constructors use this dot format so while we're really doing the same thing basically here and here objects of type function are considered constructors and constructors need to be initialized first and assigned to an instance of an object and only then they will work so that was the mistake that was making and I just wanted to put it here so hopefully it will be helpful to to many of the you know readers here viewers of my tutorials so I think I'm ready to go back to to the canvas tutorial I start creating a function constructor instead of a an object so I need to change these two columns and change the formatting a little sorry about that that was that wouldn't work if if we had equal signs I started to I I mixed it up inside creating a function constructor and instead of an object this supposed to be an object so that's I'm changing it back to that and let's see here and I don't even need this that's not going to work that's for again that's for function constructors I can just type in the names right away so I need to create a function called create and this function will take canvas tag ID let's see here so something like this and this function this is the core JavaScript how you know most in most cases how canvas is created we're just wrapping it into this nice little object that we can use later and here in this function now we can use the disk keyword and say canvas equals document get element by ID and we're going to use the canvas tag ID copy and paste it in there and this context so we're basically taking these local parameters and we're setting them to something inside this function again was so now that we got canvas we got it by using the get element by ID function canvas tag ID was passed to it so now we need to use this canvas variable property that we just created to grab its context so it's going to this canvas tag ID is going to be the ID canvas so it's this element we're grabbing this element of this canvas and now we're going to get its context so this can be done by saying this canvas get context and here we're going to say 2d it could have been 3d but we're making a two-dimensional demo here for now and then this function needs to return this context so we created this object now we're going to initialize it and so now we can start to initialize our code and because this is not a function constructor we don't have to create a new object using the new keyword we can start using it right away because this is the JSON format we just typed in the context the content the content of these the content of this object by hand in between brackets so it already exists all these things the context object already exists so we can start calling its function create and this really makes it so much simpler it's contact create and it tells you exactly what it does it hides all of this code in here and we need to pass the canvas tag ID now we're not using the hash tag here we don't have to because remember get element by ID it just gets the string so this canvas here that's the reference to canvas ID in HTML the ID tag and you just call create function it runs these the this keyword inside a function inside a you know JSON object this will refer to these properties here using this keyword inside this function it will just refer to these other properties in the same object it's not referring to the function and the actual object html5 context object will be stored in this parameter so we can access it as context context I know that's a little redundant probably but as long as we keep in mind that this is the main context custom context JavaScript object that we created it's really fine it's it is a little redundant but it doesn't really matter sometimes you have to choose one style of programming for your project and stick to it we could have created these variables as global variables and have them available through our entire JavaScript program but it's just out of a habit it just I start creating everything as objects creating custom objects when your project grows that's when it becomes much more useful you you start using objects and you you'll definitely make your code much more readable if you use these you know if you structure your code in this way so now that we have created the context let's let's do something with it and for example this is the handle now to this entire canvas from our JavaScript program not that we created it and let's maybe paint the background that's the most basic thing you can do with that canvas is painting the background in a certain color we're going to use the context that we created remember this parameter now it's a actively attached to the canvas as a handle so we can use it to access canvas one of the first things before painting the background we need to call begin path and it's kind of hard to explain what begin path really does because in this example it's not really going to make a difference but that's only because we're drawing one thing on the screen begin path usually becomes more important when you have different shapes for example lines and then you draw rectangles then you draw a circle or something and for each one shape you need to reset the path and that's what this function does because otherwise if you don't call it it's going to think that you're continuing to draw using you know the preferences that you set for the so-called path in the previous object and sometimes you just want to start a completely new object with new properties that's not even part of the previous one so you have to always clear the path but because we're only clearing the background here in this example it's not going to matter if it's there or not but it's still a good idea to to get in the habit of starting using it anyways so to draw something we use the function rect rectangle and we're going to use the same 640 by 480 parameters and context context fill style let's do a black black screen context context fail and so you need all these three functions three commands rather three statements to draw something on the screen two to fill it in black color now here we set the dimensions of the black rank rectangle let's see what happens if I run the code as you can see it turned black so we successfully will just painted the background block and again the begin path is we don't really need it as you may see if I comment it out and I run it again still it's still painting it's not really having any effect but if for example in videogames there's a loop you keep drawing things in your loop so if you start drawing a line here and you assign red color and a certain thickness and then that loop returns back here and we don't begin paths again it's going to think that we're just continuing to this drawing the the line drawing process it's going to continue thinking we're still drawing the line so that's why it's important to set to begin path each time we start drawing something new it simply resets everything to draw a new shape so this concludes this tutorial we created canvas in HTML we added the context object we initialized some canvas and context properties with get context and this is the basic setup and then we in jquery's after everything is loaded up we actually created the context and we use that context to draw something on the canvas so this is a really basic canvas tutorial this is just a starting point and within the next tutorials I will show you how to draw sprites how to animate characters how to jump around the keyboard to basically make a really simple game in html5 so I hope you guys like this tutorial and I'll see you next time

37 Replies to “JavaScript HTML Game Development Tutorial 1 – Javascript Game Tutorial (Canvas)”

  1. Allan Cheah

    Well presented! App is always a good topic to discuss.

    Anyway, is it ok if i can get your advice on these android app I have posted below? I am still a beginner and hope to learn from you. Your feedback is greatly appreciated!…

    bit. ly/2TGCU1T

    So sorry about the shortened link having spaces. Will greatly appreciate if you could remove the spaces to access this google play store app.

    appreciate ya !!

  2. kensley lewis

    Fundamentally there are no real function constructors in JavaScript. javascript is a prototypical language. so initaliazing a new instance to access properties should be avoided. instead making use if object literals and linking objects together should be the way to go.

  3. Cam SB

    your intermission to explain the difference between JSON objects and object constructor functions…… I learned something new that I hadn't understood before. Thanks!

  4. Mango Pip

    Erm. a little help…
    When i defined
    create : function(canvas_tag_id)
    this.canvas = document.getElementById(canvas_tag_id);
    this.context = this.canvas.getContext('2d');
    return this.context;

    The console said it cannot read property 'getContext' of null?
    This might have a very simple solution to it, but i'm new to javascript.
    An explanation would be very helpful!

  5. Giancarlo Andre Bravo Abanto

    2 year ago when l was looking at this code l didnt understand most of things. but now is easy to understand for me. the key is to get practice and be constant. and a bit of knowledge of objects

  6. AlexEEZ BG

    Plz help me with mistakes in my code:

    "start.html (HTML) code":

    <canvas id = "canvas" width = "640" height = "480"
    style = "border: 1px solid gray; width: 640px; height:480px;"

    "game.js (JavaScript) code":

    var Context = {
    canvas : null,
    context : null,
    create : function (canvas_tag_id) {
    this.canvas = document.getElementById (canvas_tag_id);
    this.context = this.canvas.getContext ('2d');
    return this.context;
    $(document).ready (function() {

    Context.create ("canvas");

    Context.context.rect (0, 0, 640, 480);
    Context.context.fillStyle = 'black';

    (Ps: I'm using a program called brackets;
    Also "canvas_tag_id" in "this.canvas = document.getElementById (canvas_tag_id);" is not in colour (It's black). Plz Help?)

  7. Marble League

    I've had a fun idea for a game bouncing around in my head for months. I've put together notes, spreadsheets, images, maps, all sorts of stuff, but have struggled figuring out how to actually build it. I've made some progress lately, but I hope your tutorial series may help me along further. Really excited to dive in!

  8. Kaito Hiroyuki

    I don't really know if you are still responding to comments after 2 years, but I am wondering, Why do you need to getContext('2d')? And do I need to use double quotation " or single '? ( sorry, I am not english native )

Leave a Reply

Your email address will not be published. Required fields are marked *