Kanbritech Learn logo
HTML HTML Graphics 45h track

HTML Canvas

Write a red rectangle at coordinate 10,20 with width 80 and height 40.

Understand the topic

Canvas provides a bitmap drawing surface controlled with JavaScript. Set the element width and height for the drawing coordinate system, then obtain a rendering context. CSS can resize its display but does not change the underlying drawing resolution. Canvas pixels do not create semantic elements, so provide equivalent text or data for information conveyed by the drawing.

Worked example

<canvas id="chart" width="300" height="130" role="img" aria-label="Workshop places: HTML 12, CSS 8">Workshop places: HTML 12, CSS 8.</canvas>
<p>HTML: 12 places. CSS: 8 places.</p>
<script>
const ctx = document.querySelector("#chart").getContext("2d");
if (ctx) {
  ctx.fillStyle = "#15803d"; ctx.fillRect(20, 20, 240, 30);
  ctx.fillStyle = "#0369a1"; ctx.fillRect(20, 70, 160, 30);
}
</script>

fillRect draws a rectangle from x,y with a given width and height. The paragraph supplies the same data as the bars so the values are not available only as pixels.

Practice

Write a red rectangle at coordinate 10,20 with width 80 and height 40.

Show a suggested answer
ctx.fillStyle = "#b91c1c";
ctx.fillRect(10, 20, 80, 40);

Common mistake

Do not stretch a small canvas with CSS and expect sharper pixels. Drawing-buffer dimensions and display dimensions are different.

HTML documentation

Live Example

Try Coding

Result