CKTIS / JavaScript
Canvas 2D: clear a region and draw a filled circle
Separate clearing pixels from resetting the path. Build a circle with `arc()`, choose a paint with `fillStyle`, and render its interior with `fill()`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const ctx = canvas.getContext("2d"); // CanvasRenderingContext2D or null
ctx.clearRect(x, y, width, height);
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.arc(x, y, radius, startAngle, endAngle, counterclockwise);
ctx.fillStyle = style; // CSS color string, CanvasGradient, or CanvasPattern
ctx.fill();
ctx.fill(fillRule);
ctx.fill(path);
ctx.fill(path, fillRule); // path: Path2D; fillRule: "nonzero" or "evenodd"CanvasRenderingContext2D.clearRect/beginPath/arc/fill/fillStyle groups four methods and one property (fillStyle) on a Canvas 2D context. These are web platform APIs, not part of ECMAScript 2024. On a canvas element, call canvas.getContext("2d") and check for null; availability depends on the runtime.
clearRect(x, y, width, height) erases a rectangle to transparent black on a context with alpha enabled. It respects the current transform and clipping region, but does not use fillStyle or remove the path. To clear the entire canvas with clearRect(0, 0, canvas.width, canvas.height), use an identity transform and make sure the clip excludes none of the canvas.
beginPath() empties the current path without changing pixels or paint settings. Call it before building an independent shape so the next fill() does not accidentally paint old geometry again.
arc(x, y, radius, startAngle, endAngle, counterclockwise) adds an arc centered at (x, y) without painting it. Angles are measured in radians from the positive x-axis. The default direction is clockwise; true reverses it in the default coordinate system. Angles 0 and 2 * Math.PI with the default direction make a full circle. If the path already has an endpoint, arc() adds a straight line from it to the arc’s start. If any numeric argument is NaN, Infinity, or -Infinity, arc() returns without changing the path. If all numeric arguments are finite, a negative radius throws IndexSizeError.
The fillStyle property accepts a CSS color string, a CanvasGradient, or a CanvasPattern. It defaults to black; an invalid color string leaves the previous style unchanged. Setting it does not recolor pixels already drawn.
fill() and fill(fillRule) paint the current path with the current style. fill(path) and fill(path, fillRule) paint the supplied Path2D instead. The default "nonzero" rule counts a ray’s crossings of the path with signs for direction and tests for a nonzero total; "evenodd" tests for an odd number of crossings. Filling treats open subpaths as closed without modifying them or clearing the path.
Examples
<!doctype html>
<meta charset="utf-8">
<title>Canvas 2D pixel samples</title>
<pre id="output"></pre>
<script>
const canvas = document.createElement("canvas");
canvas.width = 48;
canvas.height = 24;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("Canvas 2D is unavailable");
const rgba = (x, y) => ctx.getImageData(x, y, 1, 1).data.join(",");
ctx.beginPath();
ctx.arc(12, 12, 8, 0, 2 * Math.PI);
ctx.fillStyle = "#ff0000";
ctx.fill();
const samples = [rgba(12, 12)];
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(36, 12, 8, 0, 2 * Math.PI);
ctx.fillStyle = "#0000ff";
ctx.fill();
samples.push(rgba(12, 12), rgba(36, 12));
document.getElementById("output").textContent = samples.join("\n");
</script>Result
255,0,0,255 0,0,0,0 0,0,255,255
Save the example as an HTML file and open it in a browser. The three displayed RGBA samples are the first circle’s red center, the transparent pixel at that same position after redrawing, and the new circle’s blue center. The canvas is not attached to the page. `getImageData()` throws `SecurityError` if the canvas is no longer origin-clean, for example after drawing a cross-origin image without CORS permission; `clearRect()` alone does not restore that status.
Related lessons
- JavaScript · Lesson 27 · Intermediate · Version: 3