particles

HTML5 game development blog

<!-- a HTML5 game development blog -->

Pages

twitter account

Thursday, June 13, 2013

Tutorial 1 - Dragon of Bosnia: Basic HTML, Canvas and EaselJS - Drawing Images to Canvas

So in this first tutorial we will make a html canvas element and draw something in it with the help of the EaselJS library. Nothing interactive right now just the basic stuff so let's get started. And here is a preview picture of what our canvas will look like at the end.

tutorial 1 - canvas html preview picturee
Preview picture of our finished work in tutorial 1.


First we create a simple HTML file in which we load the necessary Javascript and create a canvas element.

The basic HTML file looks like this:

The HTML is pretty much straight forward there are just a few lines that need some explaining.

Line 8: Here we load the EaselJS JavaScript library which we will use for the interaction with the canvas element in this case we use the hosted version of the library. We could also download the library and use a local copy if we desire to. For more information on EaselJS be sure to visit: http://www.createjs.com/#!/EaselJS

Line 11: In this line we load or main.js JavaScript file where we will write our code.

Line 14: Here the onload event will call the init() function which will be executed when our document loads. We will write this function in our main.js file later.

Line 15: Finally here we create our <canvas> element we give it an id so that we can reference it later in our code and we give it the attributes width and height in pixels. We also give the canvas element a border with some basic CSS just so we can see it. And here it is our empty canvas. Does't look like much now but wait till we start drawing on it.


So that's it for our HTML we created the canvas now we go on to the real stuff writing the JavaScript in our main.js file. In this tutorial we will just load some images and draw them to our canvas. So let's get started.

We want to write our init() function which is executed when the document loads. For now we will write there the whole code that is needed to load and draw the pictures to the canvas. So here is how the init() function will look like and than i will explain it line by line.
So there you go now what is happening here.

Line 3: Here we just get the <canvas> element from our HTML file and store it into a variable called canvas for convenience and future use. We use the getElementById() method which will return the element that has the id attribute with the specified value in our case this is the <canvas> element which has the id attribute tutorialCanvas. If you want to know more about the getElementById() method here are two links:

Line 4: Here is our first encounter with EaselJS. Here we create a new Stage and we point it to our canvas variable. The stage will contain all the display objects we will be drawing. As you can see the Stage class is inside a namespace called createjs, in fact all EaselJS classes are inside that namespace. You can find out more about the Stage class in the very good EaselJS documentation:

Line 6: Here we create our image that we will draw to the canvas from the EaselJS Bitmap class and store it in the backgroundImage variable. As you can see it is also a part of the createjs namespace and all we have to do is give it a link to our image. Again here is more resource on the Bitmap class:

Line 7: Here we add our image to the display list of the stage so it can be drawn and we do this using the addChild() method. More about the addChild() method here:

Line 8: So now there is one last step we have to do. We have a display list but there is still nothing drawn on the canvas until we call stag.update(); Which will draw all the children of the stage from the display list to the canvas in our case that is just our background image.

So here it is our canvas with an image drawn to it.

alternate content

Now that we know how to draw images onto our canvas let's add some more. We will draw some trees so our heroine has a forest she can walk through. We just add these to lines to our init(); function and we add them after the background image but before the stage.update().


Now our canvas looks like this with some fancy trees drawn on top of the background.

alternate content

That is why it matters where you add the lines of code. The display objects will be drawn in order as they where added in our case the background first than the trees on top of it.

I think we should add some ground so there is something to walk on. Let's do it like we did before by adding these two lines after the trees but before the stage update.

Hmmm what happened here?

alternate content

Obviously we have to tell the canvas where we want our image to be drawn. Our previous images where roughly the size of the canvas so there was no problem but this one is drawn at the top but it  should be at the bottom. We have to give the canvas the coordinates where we want the image to be drawn with the left top corner being the x = 0, y = 0 and by default all images will be drawn starting there.

The x coordinate for our ground image looks fine but we want to move it to the bottom so we give the y coordinate a value of let's say 164 and we do it with this line of code:


Which we will add after the stage.addChild(ground); line. And here it is our final canvas with all three images drawn where they should be.

alternate content

Now that is it for our first tutorial we did some basic HTML stuff, and some fancy canvas JavaScript magic using the EaselJS library.

You can find all the code for the tutorials here:

Source code on GitHub

If you implement the code from this tutorial (or download the one from GitHub) it can happen that the first time you load the site you will see a blank canvas and you have to refresh the site to see the images drawn to it. This happens because the code loads faster than the images, so we have to preload them to prevent this from happening. We will see how to do that in the next tutorial and we will also make a fancy loading screen. So better come back. See Ya. 

74 comments:

  1. Thanks, really helped me out!

    ReplyDelete
    Replies
    1. Happy to hear that if you have any questions or suggestions feel free to tell me

      Delete
  2. Just wanted to say that the example pics of the canvas are showing up blank on chrome but work on firefox. could just be me, though.

    ReplyDelete
    Replies
    1. ^this was me, after reloading the page a few times it worked and seems to be working fine after the fact.

      Delete
    2. Hmmm... that is not supposed to happen if it occurs again plz tell me so i can try to fix it... Or if you have any other problems, suggestions or questions feel free to say so.
      Cheers!

      Delete
    3. Encountered the same issue of blank canvas in Chrome, but working in Firefox.
      Using http://code.createjs.com/createjs-2013.09.25.min.js

      Delete
    4. Does it work after you reload the page, it could be a preloading issue I'll look into it, thx for the info

      Delete
    5. Did you look into it?

      Delete
  3. so many lacking steps..,

    ReplyDelete
    Replies
    1. what you think is lacking maybe I can help out

      Delete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. The downloaded File is not working on me too
    https://github.com/AMARoso/tutorials

    ReplyDelete
    Replies
    1. Not sure what you talk about, but if you are talking about the first tutorial file when you open the html for the first time in your browser you just see a blank canvas because the images are not preloaded, just refresh the browser it should be OK, in the second tutorial you can see how to preload images so this does not happen.

      Delete
  6. thak you amar ... this are some great tutorial to get me started.

    ReplyDelete
    Replies
    1. thx man, I'm happy it's useful to you, make something great. Cheers

      Delete
  7. Hey thanks for this. I'm a Flash refugee - finally learning the new technology. I am beginning to see that this will be much better than Flash in a short while.

    ReplyDelete
  8. Great post thanks! one quick question, if I wanted to change the image size how I will do it? Thanks!

    ReplyDelete
  9. Hey!
    Great post Amar!
    I followed your tutorial and works well. However I noticed that bitmap works well when the dimensions of canvas and given background image are the same. But, when I use an image with much greater width or height, and draw that on a canvas with smaller dimensions, it seems to cut the image.
    Do you know any workout for this problem?
    Thanks again! :)

    ReplyDelete
    Replies
    1. Hi,
      It's nice the tutorial helped.
      For your question i would just resize the image in Photoshop to fit your canvas. You can do it in code by accessing the canvas width and height and giving the image the same dimensions, but it's easier to just do it in photoshop or some other image editing software.

      Delete
  10. Here i learn lots of functions of html5 games development. This post give many examples of coding which is good for understanding.

    ReplyDelete
    Replies
    1. HTML5 Training in Chennai HTML5 Training in Chennai JQuery Training in Chennai JQuery Training in Chennai JavaScript Training in Chennai JavaScript Training in Chennai Full Stack Developer Training in Chennai Full Stack Developer Training in Chennai

      Delete
  11. The best thing about HTML5 is that it allows the developers to embed the video files, audio files, and high quality graphics without any third party applications.
    html5 training in chennai | html5 training institutes in chennai | Fita Chennai reviews

    ReplyDelete
  12. Nice tutorial, This is very useful. Thanks for sharing.

    html training in chennai

    ReplyDelete
  13. PHP is the best language to develop data driven websites. PHP is used by majority of the ecommerce websites. Learning PHP can give you a great future for sure.
    PHP training in Chennai | PHP course in Chennai | PHP training institute in Chennai

    ReplyDelete
  14. Dot net is a Microsoft product so it is the best language to develop applications for windows and it is supported well on the windows platform. Dot net is prefferd globally and a renowned platform with lots of job opportunities.
    Dot net training in Chennai | .NET training in Chennai | Dot net course in Chennai

    ReplyDelete
  15. I have completely read your post and the content is crisp and clear.Thank you for posting such an informative article, I have decided to follow your blog so that I can myself updated.
    Android training in Chennai | Android course in Chennai | Android training institute in Chennai

    ReplyDelete
  16. I also benefit from learning the assessments, but learn that alot of people ought to stay on essay to try and add worth in the direction of the authentic weblog release. Niche relevant blogs

    ReplyDelete
  17. Thanks a lot game dev for sharing the gaming and cheap canvas printing tutorials. Finally I know how the basic HTML file looks like. Will recreate it all pretty soon, thanks mate for the post.

    ReplyDelete

  18. شركة تنظيف منازل وبيوت بتبوك شركة الصفا والمروه
    شركة الصفا والمروه شركة تنظيف منازل وبيوت شركة تنظيف منازل بتبوك فنحن لدينا احدث الالات والمعدات المتطوره وافضل المواد واجودها ويقوم بهذه الخدمات فريق عمل خاص ومتميز ولديه احدث الاساليب فى القيام بعمليات النظافه ونقدم جميع خدماتنا باسعار تناسب جميع العملاء دائما الناس يقعون فى مشكلات نظافة بيوتهم اما لمساحتها الكبيره او لانشغالهم بعمل ما او وجود مناسبه لديهم وبعض الامور لا يقدرون على نظافتها مثل تنظيف المسابح والخزانات فلا تحتاروا ولا تترددوا فلدى شركتنا شركة تنظيف منازل وبيوت بتبوك شركة الصفا والمروه
    شركة نقل عفش بتبوك

    ReplyDelete
  19. i am reading your blogging stuffs from long time but today i feel so happy to encourage you that you do great and on your footprints i do the same but yes i am nothing. best of luck and do great work
    Thankyou very much

    ReplyDelete
  20. I can set up my new idea from this post. It gives in depth information. Thanks for this valuable information for all,.. thebestvpn.uk

    ReplyDelete
  21. Your work here on this blog has been top notch from day 1. You've been continously providing amazing articles for us all to read and I just hope that you keep it going on in the future as well. Cheers! https://internetprivatsphare.de/prosieben-live-im-ausland-empfangen/

    ReplyDelete
  22. I genuinely believed you would probably have something useful to say. All I hear is a bunch of whining about something that you can fix if you were not too busy looking for attention. After all, I know it was my choice to read.. de beste vpn

    ReplyDelete
  23. Very cozy looking rooms. Let me know if your going to Mexico. Oh and btw. you should read our Tipping in Mexico guide if you do. It will save you a lot of awkward moments. vpnveteran.com

    ReplyDelete
  24. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you! Printers Copier Repairs

    ReplyDelete
  25. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Thanks & Regards,
    VRIT Professionals,
    No.1 Leading Web Designing Training Institute In Chennai.

    And also those who are looking for
    Web Designing Training Institute in Chennai
    Photoshop Training Institute in Chennai
    PHP & Mysql Training Institute in Chennai
    SEO Training Institute in Chennai
    Android Training Institute in Chennai

    ReplyDelete
  26. You have a genuine capacity for composing one of a kind substance. I like how you think and the way you speak to your perspectives in this article. I concur with your mindset. Much obliged to you for sharing. internet

    ReplyDelete
  27. I'm constantly searching on the internet for posts that will help me. Too much is clearly to learn about this. I believe you created good quality items in Functions also. Keep working, congrats! lemigliorivpn

    ReplyDelete
  28. Excellent website! I adore how it is easy on my eyes it is. I am questioning how I might be notified whenever a new post has been made. Looking for more new updates. Have a great day! Lexispoker

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. You have provided a nice article, Thank you very much for this one. And I hope this will be useful for many people. And I am waiting for your next post keep on updating these kinds of knowledgeable things
    Android Training in Chennai
    Android Course in Chennai
    Android Training in Bangalore
    Android Course in Bangalore
    Android Training in Coimbatore
    Android Training in Madurai

    ReplyDelete
  31. I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. domino99

    ReplyDelete
  32. Use on screen controls to move the frog. Cross the road and canal, get to the finish line to win the game. Jumpy Frog - Road Cross

    ReplyDelete
  33. I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. dokkan.pw

    ReplyDelete
  34. Thanks for sharing!
    ____________________________
    Kizi Games

    ReplyDelete
  35. Quite Interesting post!!! Thanks for posting such a useful post. I wish to read your upcoming post to enhance my skill set, keep blogging.I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    selenium training in chennai

    selenium training in chennai

    selenium online training in chennai

    software testing training in chennai

    selenium training in bangalore

    selenium training in hyderabad

    selenium training in coimbatore

    selenium online training

    selenium training



    ReplyDelete
  36. Persuading the companies to trust Salesforce thanks to its scalability and customization makes this company take the leading position among CRM services providers. ... If the client is a core then all the company's actions to achieve effective marketing, sales and customer service should be taken for the client's good.
    Salesforce Training in Chennai

    Salesforce Online Training in Chennai

    Salesforce Training in Bangalore

    Salesforce Training in Hyderabad

    Salesforce training in ameerpet

    Salesforce Training in Pune

    Salesforce Online Training

    Salesforce Training

    ReplyDelete
  37. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. ป๊อกเด้ง

    ReplyDelete
  38. I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks! เกมป๊อกเด้ง

    ReplyDelete
  39. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. วิธีแทงไฮโลออนไลน์บนมือถือ

    ReplyDelete
  40. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. สมัครเล่นไฮโลออนไลน์

    ReplyDelete
  41. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. วิธีแทงไฮโลออนไลน์บนมือถือ

    ReplyDelete
  42. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. สมัครเล่นบาคาร่าขั้นต่ำ10บาท

    ReplyDelete
  43. Minimum Baccarat bet is 10 baht with UEFA BET Baccarat . Is an online gambling website At these online gamblers Very popular Baccarat online Suitable for gamblers Who want to invest only 10 baht And the profits that have returned It may be too much that unexpected, it is possible, you have to try to experience it to know whether it is true or not, our website is easy to start, not a loss. Moreover, we have staff to take care of customers 24 hours a day. บาคาร่าขั้นต่ำ10บาท

    ReplyDelete