HTML5 Canvas and JavaScript Game Tutorial
HTML-код
- Опубликовано: 13 июн 2024
- Start the full game course at: chriscourses.com/game-course
When I first started learning web development, I was able to get text and images displaying in a browser, but when it came to developing interactive games, I was frustrated, baffled, and felt like I really wasn't made out to be a web developer. It seemed like game developers could easily whip up a fully functional game in a few files worth of code, but me, I was just an imposter.
I always attributed it to game developers being born with an innate ability to grasp mathematics and complex functions used throughout their day-to-day programming, but now I know, that's just not the case.
Through much trial and error, I eventually started putting the pieces of the game development puzzle together. I spent MONTHS studying and analyzing other developers canvas pieces, while also taking Khan Academy math courses to truly understand how math and programming work in tandem together to produce a fully functional game. I realized that game development wasn't that hard-it's just that no creators have pieced the puzzle together and presented it in a consumable manner that's easy for beginners.
This course covers everything I've learned during those months worth of learning throughout my eight years of experience. Rather than having you struggle to find the right resources and put all of the pieces together correctly (like I had to do), I've compiled everything into a few hours worth of concise, straight to the point videos, that'll get you started with all of the basics required to program your very own video game.
00:00 Project setup
09:32 Create a player
17:43 Shoot projectiles
23:18 Whiteboard projectile math
25:47 Projectile creation continues
37:58 Create enemies
51:28 Detect collision on enemy / projectile hit
57:45 Detect collision on enemy / player hit
1:00:54 Colorize game
1:11:06 Shrink enemies on hit
1:18:00 Create particle explosion on hit
1:29:20 Add score
1:38:05 Add game over UI
1:51:57 Add restart button
If anyone is curious about what happend at 38:07.
It's good to realize the difference between requestAnimationFrame and setInterval
If you go to another tab your game pauses, because requestAnimationFrame only works if tab is active .
setInterval is active regardless if you have the tab open or not. So it's gonna keep push enemies into the array of enemies every second. And that's why at 38:07 the screen was full of enemies.
How you could avoid this: Your animate() function is called already as quick as possible by requestAnimationFrame().
Make a global variable called frames = 0.
In animate() just do frames++ to count up the frames
In spawnEnemies you just have to do some easy math to see when a second passed.
Usally browsers run at 60FPS. so each 60 frames = 1 sec.
If (frames % 60 === 0) { spawnEnemies() }
this comment is pure gold
This tutorial is the first in a short list of digestible content to show developers how to code a game with just Canvas, step-by-step. I remember a few years ago trying to find something like this on RUclips, and there was none to be found. So thank you for being a pioneer
Thank you for the amazing tutorial and code along experience!
If someone wants to have the shrink animation without importing an external library, it is pretty easy:
1. You define a property "targetRadius" in your enemy's constructor
2. In the update method of Enemy, you check if targetRadius is bigger than radius and if so you shrink it by a constant value (for example: shrinkSpeed = 0.8) and you pay attention that if the substraction gets you a smaller radius than targetRadius, you set it with radius:
if (this.targetRadius < this.radius) {
this.radius =
this.radius - this.shrinkSpeed < this.targetRadius
? this.targetRadius
: this.radius - this.shrinkSpeed;
}
3. In your game loop, instead of of using the library you just substract the value to enemy.targetRadius
i’m 5 minutes in and I already love how detailed you explain everything
Very good tutorial, the learning material, the video, the sound, the explanation, everything is good. I know this tutorial could be more shorter but he does a lot of things in a purpose, and to make us understand every single of function or code. Great job. Very recommended 👊
Pls help my enemys only spawn when i shoot a projectile and evrytime i shoot a projectile they get faster
Top quality video mate. I was stuck forever figuring out the angle and you explained it so well.
That's a long one, just watched the intro, will save it for the weekend and code along. Thank you for sharing this Chris, I know it's a lot of hard work to produce content like this.
There's a lot of work in this video. From lighting, to cameras, to editing. I'm not even a 'programmer', but I'm interested in 'twine' with some javascript. (As well as streaming.) So, I'm actually as impressed more than you because he also has explanation style that's incredible.
как интересно, я постоянно встречаю ваши комментарии под самыми разными видео. Видимо мы интересуемся одним и тем же)))
+ + +
how interesting, I constantly meet your comments under a variety of videos. Apparently we're interested in the same thing)))
the real question is: did you do it?
or are you just here for traffic
@@WEBSTART-LIVE Я люблю Россию, я учился в Украине. это мой второй дом. Я надеюсь посетить Россию очень скоро
Since this came out on my birthday, I'll consider it a present. Thank you Chris you shouldn't have!
LOL
Came out a week before my birthday lol
Know this is late but happy birthday man!
I need to wait five more days
This was not only a very good Game Tutorial, it was also an excellent programming tutorial in general. Thank you for your time and dedication. I really appreciate it.
I know right!?
I love the way you omit the html, head and body tags. I consider myself an intermediate front-end hobbyist and I completely missed that part of html5 until now. Mind blown.
Chris, I watch these videos and feel inspired. Thank you for providing me with quality content. Don't listen to haters my dude.
I started making canvas experiences in 2010, and I've seen many videos/tutorials since.
This video is one of the best tuts I've seen out there.
Your code is very clean, and in my opinion, your commentary is also very good and joyful to listen to.
Keep up the great work.
It is an amazing tutorial! Clear step for the coding and math concept, thanks Chris!
What a fantastic couple of hours. I also feel like I learn so much from your videos. I especially appreciated the collision detection explanation.
Fantastic tutorial on canvas. Covers some important programming concepts. It's worth watching again. Thanks for putting this together for us.
You are an amazing teacher. earning from you did not feel like learning at all and I had fun every minute! Thanks a bunch, may you and your generations remain blessed
Very fast-paced and straight to the point! Great vid, learned loads of new tricks!
Great video style!
I like the lighting and the movement of the camera👍
I signed up for your newsletter. I am really impressed by your high quality course approach. I am looking forward to buying the rest of the course when it's ready. Thank you for your effort.
Thanks for watching 😉 Haven't had much time to keep everyone updated on the newsletter or produce the rest of the course yet, but it'll all be 100% ready by Oct. 31. Really appreciate your support and can't wait to help ya out some more.
This game is fucking awesome, and the background music is amazing, this is definitely the best html canvas game tutorial !!!
This is so amazing Chris. Seriously, you just saved me from stressing about my college assignment. I'm extracting these concepts into my MVC architecture-based app. Thank you very much!! :))
Great to hear! Coding tutorials helped me a ton in college as well, glad I could return the favor to someone else in return. Keep it up!
@@ChrisCourses Hello. Can I make this game little bit faster? It seems slower on my computer, projectiles even leave traces.
Amazing tutorial!
Very clear explained and simple to follow along
Great Job!!! Chris I am a retired programmer and spent several years in the training department (25yrs ago!). I can honestly say you do a better job then I did. I think everyone would appreciate more advanced JS GRAPHICS. I don't do much coding any more but still try to stay up to date watching good tutorials - I wish you had more :)
really appreciate it chris. the quality of your videos is another thing. please also make filming videos just like before. thank you
I've just gone through a bunch of your youtube tutorials - absolutely hooked. You've got real talent as a teacher - signing up to your courses for more ^_^
Great to hear! I did that collision detection video with about 5 hours of work, so hoping I can just keep my head down and get stuff out more consistently. Need to stop trying to perfect everything and just go with what I'm quick at.
Appreciate all the support and will be comin to support you in return with more vids 🙌
Great video Chris, I enjoyed it very much and I liked that you kept it very simple and avoided to refactor your code or make abstractions.
Dude the accomplishment I felt after finishing the tutorial is amazing, dude u made this possible for me to learn gamedev on js, thank you
such an amazing tutorial man! I coded along and did it, I'm teaching myself coding so it was a bit rough but was able to manage. the one thing Id appreciate it if you can make a video teaching us how to package the final product so we can share it with friends. thanks a lot.
This is really awesome, guy. Thank you so much for connecting the dots for beginners.
You have such an awesome video and sound quality :D and I also like the way you explain, especialy the fact that you explain in small steps :D
This is a *FANTASTIC* tutorial! Seriously, one of the best I've seen. Thank you so much for taking the time to make this. :)
Anytime, glad it was helpful! There's a continuation over on chriscourses.com if you need it-also have a side scroller course on the way to satisfy any desires there 🙌
Thanks Chris for sharing a valuable knowledge so we can have a good fundamental on how to build a game using canvas and Javascript.
The best programming tutorial I have ever seen
I am only 12 minutes in and I have learnt so much! Thank you!
Your explanation is so deep and I love it despite I couldn't get the half of it :D
The most useful video for a total newbie in game dev. Thank you.
Great tutorial as allways! Really appriciate the effort you put into these!
You are gifted when it comes to explaining things
This is an excellent tutorial Chris. You explained the process very clearly and the end result is really cool. Nice work and thanks for sharing. :-)
One of the best canvas tutorial ever
I learned so much from this video, thank you for helping me improve my JavaScript skills!
Just a fantastic tutorial. Loved watching and following along!
Hey thanks man. Had grid based game concept but didnt know Canvas all that well. This got me everything i needed to get started! Thanks.
Man, I love this video! Thanks for taking the time to make it!
this was awesome. really helped start my project. thank you. and thanks for being so great!
Good call on the setTimeout workaround for the missing array element in the loop! I usually solve this by looping through arrays in reverse-but I like this a lot because you can use forEach 🤙
Great tutorial! I love your way of explaining how things work. Great Job!
thanks I just finished this tutorial. Finished product came out good and I learned a good amount !
Fantastic tutorial, well paced and just what I needed. Thanks,
I'm done watching the tutorial, I learned a lot. Thanks Sir!
Great tutorial. I have 3 retro games I wrote in C# and this give me the information I need to migrate to run in a browser. Couple of suggestions:
1) store the ID of the spawn setInterval and call clearInterval(id) when detect game over or multiple instances of the interval will run and more and more enemies will be created per second on each restart of the game.
2) Move setting the canvas.width and height and player x and y inside the init() function to adapt to changes in browser window size when restart game.
Many thanks for the tutorial.
Great explanation and really good game. .
Especially the particle effect. Love it.
This is such a good tutorial, I'm so impressed, thank you!
Perfect tutorial. Thank You!
First off, thank you Chris for such a wonderful series of tutorials, they are all magnificent.
Now, addressing a little issue. After you restart the game, the "spawnEnemies" interval remains set, therefore, executing it again will add an extra "spawner" each time, incrementing each time the amount of enemies per period. The possible fixes for this are simple:
One would be to simply execute "spawnEnemies()" once and only once, outside of any recurrent block. Another solution takes into account that "window.setInterval()" returns an Id, which we can save in a variable at the top, say for example, "let spawnerId". Once we hit a game over, inside of the startGameBtn's event listener, we clear this old interval via "window.clearInterval(spawnerId)", and then we add the new one. Hope this helps anyone who falls into the same issue.
Again, a most humble thank you for your efforts which are tremendously appreciated!
Thank you very much for the great video! I learned HTML, CSS and even javascript functions! I made my version of the game where you can move by the X axis. I used it for my project for school and my teacher was AMAZED! Thank you so so much for the great explanation! I also found the geometry in this video very useful and helpful!
idk how to thank you... the most amazing game dev tutorial on the earth
Finally! After years of waiting! Thank you so much! I have learned the HTML canvas from you sir! And earned money using the things that you have taught.
Thank you so much! Your canvas tutorials are great!
I'm waiting for the tutorial of Collision Detections for other shape.
@Alexander Exis wed dev. Parts of my school mate's thesis that needs Canvas. I remember i sold 100lines for $50
I'm impressed. Thank you so much for this tutorial.
actually made this, great tutorial great explanations, learned a lot, keep it up!
Awesome game tutorial with wonderful explanation.
broo i am from brasil and ai love your couse. i understand much better with you. dont stoping you work.
man i was mind blown by the fade effect at 1:06:00, thanks for the great tutorial
Wow, I cannot thank you enough for 33:00 - 36:00, I have been building a similar game for a class project, and I couldn't for the life of me nail down the angle ratio! Also to answer your comment about why atan2 uses y over x is because it produces a slope m which equals rise over run or, (y0 - y1) / (x0 - x1), at least that is my understanding. Thanks again, great video!
BUG ALERT!
I think anyone who watched the video could spot the bug where when the game is stopped, the enemies KEEP SPAWNING so when you start again you just get a ton of enemies coming your way...
Took me about half an hour to figure out i had to use clearInterval() inside the spawnEnemies function.
And while we're at it, the window's event listener should be removed when the game is over and re-added when the game restarts so you wont be able to shoot projectiles when the modal is open.
Hopes this helps someone ;)
yes, really.. bro can you help me with the clear Interval I don't manage to put it in the correct place, please I would really grateful for this...
Yeah i can help you!
Firstly, in order for clearInterval to work, you need to give it an actual function reference (not an anonymous arrow function). I extracted the nameless function he used in the video - spawnEnemies, and made it into its own function and called it spawnEnemiesFunction. Then, i used const spawnEnemiesInterval = setInterval(spawnEnemiesFunction, 1000) to actually spawn enemies each second.
Now, when the game ends (the player loses), i call my endGame() function, which is responsible for the cleanup.
inside it, i use clearInterval(spawnEnemiesInterval), and i also remove the event listener from the window object via removeEventListener method.
really hope this helps :)
feel free to ask any more questions!
@@dandandrorivolleyball wow thx
could you write down the code in the comments please? I can't really understand how I should input clearInterval() into my code.
This is a common mistake for people making games in HTML5
That is why "requestAnimationFrame" is always better than "setInterval" or "setTimeout" to create game loops because it is only called when the window is active.
Also, All events run in parallel to the base JS code, It's like they were different applications running at the same time as everything else, so you must be careful how you use them, else you might get into an unwanted state, and get errors or bugs from there.
Thanks Chris, this is impressive.
I added a few things to mine.
Every 10 "kills", you go up one level. This makes enemies spawn faster and move quicker
You start with 3 lives, and they go down each time you're hit. If you run out of lives, its game over
Every 3 levels, you gain 1 extra life, up to a maximum of 5 lives at any one time
And then just some visual things like the player flashing red when hit and things of that nature
how do you make the enemies move quicker?
@@sebastianrechtman3749 Its been a while at this point so I don't 100% remember, but I think I made an Enemy Speed variable and multiplied that on the x and y angles when an enemy is spawned. Then over time that variable increases so the enemies get faster
@@isthereanexho can you share the code for this?
bro, your canvas tutorial and this video really helped me, thanks a lot
Отличное видео ! Thanks. I'll add it to my bookmarks
Good content, clear explanation. I dont even want to build games, but the overall knowledge will be helpful.
I made this game completely.
Thank you very much and best wishes.
I want many more videos from you
Can You share me with the source code please
I’m Japanese so I can study Programming and English in this video.
Thank you very much.
man you are great,
i even speak english very well and i can understand all you speak.
Thank you very much for your time
Hi from Brasil. :)
Eae carai🇧🇷
awesome teaching style! I just love you.
You are a great teacher, thank you so much!!
This is exactly what I needed
Excellent tutorial, thank you. 👍
Mans looking beefed up! Great tutorial man.
Just finished. Thank you for this
Hope there will be more tutorials like this
Thanks so much for creating amazing content. I've learnt a lot from your contents
The best lesson to start learning JavaScript.
Thank you so much sir for this wonderful project
Congratulations, amazing video!
It's very useful for me, thank you.
As Ive progressed in my code learning, my thought is that this video should be shown to any new coder as required material. It introduces and explains with direct results key concepts not only for JavaScript, but all object oriented coding. As a new coder, being able to see direct results not only instills understanding but also confidence. This video is better than all of the tutorials Ive ever taken on JavaScript. 100% pure gold.
Wow, awesome comment... really appreciate this one. I too agree beginners should take this, wish I had it when I was first learning game dev! Anyways, thanks again, nice comments like this always make me feel great 😄
I was finding a tutorial to create a simple game with javascript, but look, what I found! A simple but professional looking amazing game with step by step explanation. Thanks
Thank you for this great tutorial!
I've learned a lot from this. I added a counter for how long it takes to get to level 2, 3 and so on. I let spawn double enemies if reached max. Level, but you also have double projectiles xD amazing what you can do if you're in it
Chris, this the best beginner course I've come across for HTML5 Canvas game development.
For me, what makes it so accessible is the easy peasy approach to Pythagoras' theorem and the setting of the velocity objects properties.
Just as an aside, obviously you'll be aware that the code you've produced has a lot of duplicate functionality among you game pieces and that a single game piece class could be created from which all the others extend and specialize from.
I was thrown by your introduction that this would be vanilla javascript and then you introduced a third party graphics engine for shrinking the enemies. Couldn't you have coded this yourself?
But all in all this was top drawer, thanks again Chris.
Yeah man, I considered adding inheritance and imports to reduce the amount of code in the main file, but decided not to since it usually adds another layer of complexity and abstraction that makes things hard to change once your game gets bigger and bigger. I’m actually a programmer who leans more towards duplication than trying to abstract things consistently since it does have potential to affect so many parts of your game, app, whatever code you’re working on. Figured it would be easier for beginners too rather than have to delve into more strict OOP techniques. GSAP library not being vanilla makes sense though, I just hate animating with anything else hah. Really glad you enjoyed everything though, tried my hardest to make this one of the best 🥳
@@ChrisCourses
Fair do's Chris. I've got a degree in computing and many of my fellow students really struggled with OOP although I had taught myself OOP before I went to university and found it a breeze. The caveat with inheritance is to try to avoid fragile base classes WHICH WILL break your code base. But used judicially and correctly it'll reduce code.
I've been experimenting with HTML5 Canvas animation for the last few months and much prefer to build my own transition and transform modules but hey that's me.
Cheers for your reply and I've subscribed and look forward to more animation content from you. Well done mate.
Bruhhhh i love that , I did exactly as you and I’ve got the same result 🥺🥺😍
Bless up🔥🙏🏽
This video is amazing. Always thought html canvas and js arent good enough for building games. Obviously i was wrong and just didnt know any better.
Having tutorials like this available to everyone for free really makes me happy. Thank you again for sharing your skills, lessons and wisdom.
This is a great video, thank you!
Chris you are my best teacher
I made something like this for my final project in my web dev course, lol. Didn't even know there was a full-blown tutorial for the thing I was creating.
you deserve millions subs 🔥🔥🔥
You leave a lot to the automatic sorting of the browser, like just using the tag without putting it in the head, and not using semicolons in js. You are the first tutor to do this and I hear all the time how it's bad practice. But I respect that you have your own style and thank you for the very elaborate step-by-step.
Nice little tutorial, well paced instructions...i found when it came to looping over the enemies and then the projectiles the code was glitchy...sometimes projectiles would pass trough and enemies wouldnt remove properly....it simply replaced with a generic for loop for both and spliced within there and that fixed it...like the other users have said its generally not good practice to remove from an array while looping over it. Well done though, very good and reminds us how quickly JS/Canvas games can be pulled together.
awesome video, explained very well
Excellent presentation! I particularly liked how you used trigonometry. From a trigonometry teacher.