Learn it
<canvas> is a drawing surface. Get its 2D context and draw rectangles, circles and text. (0, 0) is the top-left; y grows downwards.
π§° Tool: a free online editor such as CodePen or JSFiddle, or a plain text editor and your web browser.
Code examples
HTML
<canvas id="game" width="480" height="320"></canvas>
JavaScript
const canvas = document.querySelector("#game");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#0f172a";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#22c55e";
ctx.fillRect(40, 240, 60, 40);
ctx.beginPath();
ctx.arc(240, 120, 30, 0, Math.PI * 2);
ctx.fillStyle = "#facc15";
ctx.fill();
ctx.fillStyle = "white";
ctx.font = "20px sans-serif";
ctx.fillText("Score: 0", 10, 25);
Project: Draw a scene
- Draw ground, a sun and a player box.
- Add text.
- Draw 10 stars with a loop and Math.random().
Challenge: Draw a house with triangles using moveTo/lineTo.