Canvas Drawing
The getContext('2d') method returns the drawing context object that holds every method and property you use to paint on a canvas.
What Is a Drawing Context?
The canvas element itself is just a container - it has no draw methods of its own. To actually paint pixels you need its drawing context, an object you retrieve by calling canvas.getContext("2d"). This returns a CanvasRenderingContext2D instance that holds every drawing method, every style property, and all of the current state canvas uses to paint. Canvas also supports other context types such as "webgl" for 3D graphics and "bitmaprenderer" for transferring decoded images, but "2d" is the one you'll use for everyday shapes, text, and images.
What the Context Gives You
- Drawing methods like fillRect(), strokeRect(), and clearRect().
- Style properties like fillStyle, strokeStyle, lineWidth, and font.
- Path methods like beginPath(), moveTo(), and lineTo() for custom shapes.
- Transform methods like translate(), rotate(), and scale().
- State methods save() and restore() for snapshotting style settings.
Example
<!DOCTYPE html>
<html>
<body>
<canvas id="shapes" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById("shapes");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "orange";
ctx.fillRect(20, 20, 100, 80);
ctx.strokeStyle = "black";
ctx.lineWidth = 4;
ctx.strokeRect(150, 20, 100, 80);
ctx.clearRect(40, 40, 30, 30);
</script>
</body>
</html>The Context Persists Across Calls
The context object is stateful: once you set ctx.fillStyle = "red", every fill you perform afterward uses red until you change it again. getContext("2d") always returns the exact same object for a given canvas, so calling it repeatedly is both safe and cheap - most programs call it once at the top of a script and reuse the same ctx variable everywhere.
Example
<!DOCTYPE html>
<html>
<body>
<canvas id="palette" width="400" height="120"></canvas>
<script>
const ctx = document.getElementById("palette").getContext("2d");
const colors = ["#e63946", "#f1a208", "#2a9d8f", "#264653"];
colors.forEach((color, i) => {
ctx.fillStyle = color;
ctx.fillRect(i * 100, 0, 100, 120);
});
</script>
</body>
</html>Example
<!DOCTYPE html>
<html>
<body>
<canvas id="snapshot" width="300" height="150"></canvas>
<script>
const ctx = document.getElementById("snapshot").getContext("2d");
ctx.fillStyle = "teal";
ctx.fillRect(10, 10, 100, 100);
ctx.save();
ctx.fillStyle = "gold";
ctx.globalAlpha = 0.6;
ctx.fillRect(60, 40, 100, 100);
ctx.restore();
ctx.fillRect(180, 10, 100, 100);
</script>
</body>
</html>Exercise: Canvas Drawing
What is the purpose of calling beginPath() before drawing a new shape?