Перейти до основного вмісту
← 📄 HTML & the platform·Модуль A4 · Урок 9
ЗавданняAdd a <canvas id='c' width='200' height='100' aria-label='A blue square'></canvas>. Then in JS, get its 2D context, set fillStyle to '#3B82F6', and fillRect(10, 10, 80, 80).

<canvas>: вступ до графіки на рівні пікселів

100 XP8 min
Теорія

When pixels matter

<canvas> is a JS-driven drawing surface. Use it for charts (Chart.js), games, custom photo editing, image processing — anywhere you need pixel control that HTML/CSS can't give you.

<canvas id="chart" width="400" height="200" aria-label="Sales chart"></canvas>
<script>
  const ctx = document.querySelector("#chart").getContext("2d");
  ctx.fillStyle = "#3B82F6";
  ctx.fillRect(20, 50, 100, 100);
  ctx.beginPath();
  ctx.arc(250, 100, 40, 0, Math.PI * 2);
  ctx.fillStyle = "#22C55E";
  ctx.fill();
</script>
  • `width` / `height` — set on the element, NOT in CSS. They define the internal coordinate system. CSS sizes only stretch the rendered output (and can blur it).
  • `aria-label` — canvas is invisible to screen readers. The aria-label is the ONLY thing they can read.
  • `getContext("2d")` — the 2D drawing API. There's also webgl and webgl2 for 3D.

When NOT to use canvas

  • For shapes you could do with SVG → use SVG (scales, accessible, CSS-styleable).
  • For text → use <p>, not fillText(). Canvas text isn't selectable or screen-reader-readable.
  • For "fancy buttons" → use CSS, not canvas. Buttons need focus, hover, keyboard. Canvas gives you a pixel rectangle.

<canvas> is for problems where you actually need pixel control. For most UI, plain HTML+CSS is better.

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.