You may have heard of HTML5 Canvas, but what exactly is it? Let's figure it out together!
Canvas has many methods for drawing, you can make loads of things like squares, boxes, paths, text, images, and more! Luckily, canvas is also fully supported by most modern browsers, even Microsoft Edge, if that's your thing. To create a canvas, you'd start out with something like this:
<canvas id="gameScreen" width="800" height="600"></canvas>
<canvas id="gameScreen" width="800" height="600" style="border:1px solid black;"> </canvas>
That would result in something like this
On this canvas, you can venture in many directions. If you wanted to simply draw a line across, you could do this
const canvas = document.getElementById("myCanvas"); const context = canvas.getContext("2d"); context.moveTo(0, 0); context.lineTo(800, 600); context.stroke();
It looks like there's a lot going on here, so I'll break it down line by line.
- The next line is invoking the getContext() method on our canvas, which returns an object that provides methods for drawing on our canvas! In this case, I pass in the argument "2d", which is recognized by the method and returns the correct object which allows us to draw in our 2d space. There are other ways of utilizing tools for drawing in 3D spaces as well, check out WebGL for more on that!
These last 3 lines are just invoking methods on our context. Side note: Many developers will shorten context with "ctx", so keep that in mind when googling more about it all.
- context.moveTo is taking two parameters here, this is the X and Y position on our canvas to start drawing. Web pages start with (0, 0) as the top-left most corner. This is very important to remember, as most methods need to know your X and Y position.
- context.lineTo is again, taking an X and Y position, and it's simply creating our line to follow from our "moveTo" position, and our "lineTo" position. Think of this like drawing with pencil and paper. You move your hand to the top left, then draw down to the corner. Since the size of our canvas is 800 X 600, top left is (0, 0), so bottom right is our (800, 600).
- context.stroke is just making the physical line that you see, by following the the moveTo position, to the lineTo position.
This is a very basic example of using canvas, but I plan to dive deeper into this soon. Something that inspired me to start learning to use canvas is actually Cross Code.
For a really great walk-through of developing a block breaking game, I highly recommend this freeCodeCamp video.