Canvas sample: draw a simple scene
This complete example connects HTML, JavaScript, coordinates, fill colors, and fallback content to draw a simple scene.
What you will learn
- How the HTML and script parts fit together
- How to draw more than one shape in order
- How to keep a text explanation beside visual output
HTML
<canvas id="scene" width="320" height="180">
A blue sky, green ground, and yellow sun are shown here.
</canvas>
<p>The scene shows a sun above a green ground.</p>JavaScript
const canvas = document.querySelector('#scene');
const context = canvas?.getContext('2d');
if (context) {
context.fillStyle = '#bfdbfe';
context.fillRect(0, 0, 320, 180);
context.fillStyle = '#86efac';
context.fillRect(0, 130, 320, 50);
context.fillStyle = '#facc15';
context.beginPath();
context.arc(250, 55, 28, 0, Math.PI * 2);
context.fill();
}The background is drawn first, then the ground, then the sun. Later shapes can cover earlier shapes, so draw in the order that matches the intended layers.
How to extend it
- Change the colors and coordinates one at a time.
- Extract repeated drawing work into functions.
- Keep the text description accurate if the scene changes.
- Use animation only after the static version is understandable.