iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

HTML Canvas

The <canvas> element is a blank bitmap surface you draw on with JavaScript. It's used for charts, games, image editing, and procedural graphics.

Two-step setup

  1. Add a <canvas> to the HTML with a width and height.
  2. Grab its 2D drawing context in JavaScript and call drawing methods.
<canvas id="cv" width="300" height="120"></canvas>
<script>
    const ctx = document.getElementById('cv').getContext('2d');
    ctx.fillStyle = '#04AA6D';
    ctx.fillRect(20, 20, 100, 60);
    ctx.fillStyle = '#fff';
    ctx.font = '18px Verdana';
    ctx.fillText('Hello!', 35, 58);
</script>

Useful 2D context methods

MethodDraws
fillRect(x, y, w, h)Filled rectangle.
strokeRect(x, y, w, h)Outlined rectangle.
beginPath() / moveTo() / lineTo() / stroke()Custom path.
arc(x, y, r, start, end)Circles and arcs.
fillText(text, x, y)Text.
drawImage(img, x, y)An image or another canvas.
Canvas vs SVG: Canvas is a bitmap — fast at thousands of moving particles, but you can't restyle individual shapes after drawing them. SVG is a vector DOM tree — easier to style and animate per shape, but slower at massive numbers of objects.

Example

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML Canvas</title>
</head>
<body>

<h1>HTML Canvas</h1>
<p>This is a demo page for the "HTML Canvas" lesson.</p>

</body>
</html>
Try it Yourself »

Exercise

Create a 600×400 drawing surface that JavaScript can target.

< id="paint" width="600" height="400"></ >

Test yourself

Q1. <canvas> draws via…
Q2. Set canvas size with…
Q3. Get the 2D context with…

Discussion

Loading…