Hello!
I would recommend you first start with learning how to do Object-Oriented Programming in JavaScript. If you listen to other JS developers online, you will hear a lot about how Functional Programming is so much better than OOP. Those people usually do not make games and their opinion on OOP can be ignored. OOP is the best fit for games since most things in the world can naturally be represented as objects.
So you learn how do OOP using classes in ES6. Now you can represent things in your game as objects such as a Player, Enemy etc.. You can use inheritance if you need multiple objects to use the same foundation. For example, in my games every object inherits from an Entity class, which contains an update/draw/destroy function.
Use the ES6 module system since it's the modern way to handle multiple imports in JS today. I like to name my modules after their class names like this:
player.class.js: export default class Player { } game.js: import Player from './player.class.js'; const player = new Player();
This is my own personal opinion and many people do not agree with me, but I think it's okay to use fake encapsulation in JS as long as it is only done for code organization and you understand it doesn't actual protect the variables.
export default class Player { constructor() { this._x = 0; // _ implies private, so don't access this member outside the class this._y = 0; } }
Then you decide on what type of rendering engine you want.
- For 3D games, Three.js is the best choice.
- For 2D games, you can either use Pixi.JS if you prefer a more graph based scene setup like in Unity.
- Work directly with 2D canvas which gives you the most versatility.
Here is a really simple example how to draw an image on a 2D canvas:
<html><body><canvas></canvas><image src="./test" /> <script> const image = document.querySelector('image'); const canvas = document.querySelector("canvas"); const context = canvas.getContext("2d"); canvas.width = 500; canvas.height = 500; context.drawImage(image, 50, 50); </script></body></html>
I prefer to load images using the Javascript fetch command rather than embedding them in the document.
You can create a "main loop" for your game using requestAnimationFrame:
let lastTime = 0; const update = time => { const elapsedSeconds = Math.min(maxTimestep, (time - lastTime) / 1000); lastTime = time; // Update and draw your entire game here update(); draw(); requestAnimationFrame(update); }
And that's pretty much it. The 2D canvas can be used to make both games like this with bitmap graphics or vector-based games using primitive line/shape drawing.