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. 

80 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. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.

      Spring Training in Chennai

      The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      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. best wishes of good health and Obat Aborsi
    I really like once you make delicious homemade articles in read and understood easily in public, thank you very much for share very good article and amazing once

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

    ReplyDelete
  10. 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
  11. 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
    2. شفط الصرف الصحي بالدمام
      اقبل الشتاء وسيواجه اهالى مدينة الدمام مشكلة من اصعب واخطر المشكلات المتعبة
      أولها انسداد بيارات المجارى وانسداد شبكات الصرف الصحى وهى المواسير
      و يعانى من هذة المشكلة الجميع ويظلون فى البحث عن شركة رائدة متخصصة فى اصلاح كافة المشاكل الخاصة باعطال انسداد المجارى
      ونحن شركة تسليك مجارى بالخبر لدينا من الخبرات الكبيرة التى نكتسبها من اعمالنا السابقة نؤكدلك عملينا العزيز أننا وبكل جدارة وخبرة
      افضل شركة تسليك مجارى بالدمام رخيصة التكلفة وفى نفس الوقت ماهرين فى العمل
      تعمل الشركة بافضل الطرق الحديثة والاساليب المتطورة علي ايدي افضل العاملين والمتخصصين في هذا المجال
      حيث ان الشركة تمتلك طاقم عمل مدرب علي اعلي مستوي علي ايدي خبراء ماهرين وفنيين محترفين
      حيث لاتتواجد هذه المواد الخاصة بالعمل الا داخل شركتنا فقط وهذه واحده من اهم ما يميز
      افضل شركة تسليك مجارى بالدمام عن غيرها من باقي الشركات الاخرى المنافسة فى المجال
      كما يوجد لدينا العديد من الخصومات الهائلة فنقدم خدماتنا باقل الاسعار التى تتناسب مع جميع عملائنا الكرام
      يوجد لدينا فنيون ومهندسون وخبراء مدربون على اعلى مستوى
      وذلك حيث يمكنهم معرفة تحديد الاسباب التى تتسبب فى انسداد المجارى ولان من اصعب الاشياء هو انسداد المجارى الخاصة بالمنزل فهو يوقف الحياه بالمنزل
      و يتسبب فى مشاكل فى غاية الخطورة لاننا دائما نستعمل الحمامات والمطابخ
      وعند انسداد المجاى تتوقف الحياه كما ينتج عنها الروائح الكريهه التى تضر بالمنزل
      وايضا انسداد المجارى وذلك ينتج عنها اضرار خطيرة بالمنزل نفسه من تسربات بالمياه وتحت البلاط وتسربات بالجدران
      فلا تقلق عملينا العزيز من كل ذلك فلدينا المهارة والخبرة العالية فى اعمالنا لحل كل ذلك .

      Delete
  12. 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
  13. Nice tutorial, This is very useful. Thanks for sharing.

    html training in chennai

    ReplyDelete
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. شفط الصرف الصحي بالدمام
    اقبل الشتاء وسيواجه اهالى مدينة الدمام مشكلة من اصعب واخطر المشكلات المتعبة
    أولها انسداد بيارات المجارى وانسداد شبكات الصرف الصحى وهى المواسير
    و يعانى من هذة المشكلة الجميع ويظلون فى البحث عن شركة رائدة متخصصة فى اصلاح كافة المشاكل الخاصة باعطال انسداد المجارى
    ونحن شركة تسليك مجارى بالخبر لدينا من الخبرات الكبيرة التى نكتسبها من اعمالنا السابقة نؤكدلك عملينا العزيز أننا وبكل جدارة وخبرة
    افضل شركة تسليك مجارى بالدمام رخيصة التكلفة وفى نفس الوقت ماهرين فى العمل
    تعمل الشركة بافضل الطرق الحديثة والاساليب المتطورة علي ايدي افضل العاملين والمتخصصين في هذا المجال
    حيث ان الشركة تمتلك طاقم عمل مدرب علي اعلي مستوي علي ايدي خبراء ماهرين وفنيين محترفين
    حيث لاتتواجد هذه المواد الخاصة بالعمل الا داخل شركتنا فقط وهذه واحده من اهم ما يميز
    افضل شركة تسليك مجارى بالدمام عن غيرها من باقي الشركات الاخرى المنافسة فى المجال
    كما يوجد لدينا العديد من الخصومات الهائلة فنقدم خدماتنا باقل الاسعار التى تتناسب مع جميع عملائنا الكرام
    يوجد لدينا فنيون ومهندسون وخبراء مدربون على اعلى مستوى
    وذلك حيث يمكنهم معرفة تحديد الاسباب التى تتسبب فى انسداد المجارى ولان من اصعب الاشياء هو انسداد المجارى الخاصة بالمنزل فهو يوقف الحياه بالمنزل
    و يتسبب فى مشاكل فى غاية الخطورة لاننا دائما نستعمل الحمامات والمطابخ
    وعند انسداد المجاى تتوقف الحياه كما ينتج عنها الروائح الكريهه التى تضر بالمنزل
    وايضا انسداد المجارى وذلك ينتج عنها اضرار خطيرة بالمنزل نفسه من تسربات بالمياه وتحت البلاط وتسربات بالجدران
    فلا تقلق عملينا العزيز من كل ذلك فلدينا المهارة والخبرة العالية فى اعمالنا لحل كل ذلك .

    ReplyDelete

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

    ReplyDelete
  21. 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
  22. SKARTEC Digital Marketing Academy is an institute dedicated to meet the integrated marketing needs of the industry. Our Digital Marketing Course in Chennai is ideal for those, who wish to manage a successful and sustainable digital marketing strategy.

    This digital marketing certification explores all the core digital marketing and management concepts, techniques and disciplines from planning, implementation and measurement to success and failure factors. Enrolling in this marketing course will prepare you to join an exclusive community of highly-recognized digital marketing experts.

    Digital Marketing Course in Chennai
    Digital Marketing Training in Chennai
    Online Digital Marketing Training
    SEO Training in Chennai
    Digital Marketing Course
    Digital Marketing Training
    Digital Marketing Courses

    ReplyDelete
  23. we repair and service all models of oneplus Service in Chennai, We rely on customer satisfaction. We can service all problems faced by oneplus customers in chennai.


    Oneplus Service Center in Chennai | Oneplus Service Centre | Oneplus Service Center | Oneplus Service Center near me | Oneplus Service Center in velachery | Oneplus Service Chennai

    ReplyDelete
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. Thank you for your post, I look for such article along time, today i find it finally. this post give me lots of advise it is very useful for me. Jumpy Frog

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

    ReplyDelete
  35. thanks for your information really good and very nice web design company in velachery

    ReplyDelete
  36. 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
  37. 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
  38. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. Jumpy Frog - Road Cross

    ReplyDelete
  39. 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
  40. 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

  41. You write this post very carefully I think, which is easily understandable to me. Not only this, but another post is also good. As a newbie, this info is really helpful for me. Thanks to you.
    Tally ERP 9 Training
    tally classes
    Tally Training institute in Chennai
    Tally course in Chennai

    ReplyDelete
  42. i am browsing this website dailly and get nice facts from here all the time

    ReplyDelete
  43. Thanks for sharing!
    ____________________________
    Kizi Games

    ReplyDelete
  44. Nice! you are sharing such helpful and easy to understandable blog. i have no words for say i just say thanks because it is helpful for me.







    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery









    ReplyDelete
  45. 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
  46. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    Artificial Intelligence Training in Chennai

    Ai Training in Chennai

    Artificial Intelligence training in Bangalore

    Ai Training in Bangalore

    Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad

    Artificial Intelligence Online Training

    Ai Online Training

    Blue Prism Training in Chennai

    ReplyDelete
  47. 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
  48. 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
  49. 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
  50. 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
  51. 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
  52. 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
  53. 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
  54. 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