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

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