The CanvasRenderingContext2D.reset()
method of the Canvas 2D API resets the rendering context to its default state, allowing it to be reused for drawing something else without having to explicitly reset all the properties.
Resetting clears the backing buffer, drawing state stack, any defined paths, and styles. This includes the current transformation matrix, compositing properties, clipping region, dash list, line styles, text styles, shadows, image smoothing, filters, and so on.
This example shows how we can use reset()
to completely clear the context before redrawing.
First we define a button and a canvas.
#toggle-reset {
display: block;
}
<button id="toggle-reset">Toggle</button>
<canvas id="my-house" width="500" height="200"></canvas>
The code first gets a 2d
context for the canvas. It then defines functions that can use the context to draw a rectangle and a circle, respectively.
const canvas = document.getElementById("my-house");
const ctx = canvas.getContext("2d");
function drawRect() {
ctx.lineWidth = 10;
ctx.strokeRect(50, 50, 150, 100);
ctx.font = "50px serif";
ctx.fillText("Rect!", 70, 110);
}
function drawCircle() {
ctx.lineWidth = 5;
ctx.beginPath();
ctx.arc(300, 100, 50, 0, 2 * Math.PI);
ctx.stroke();
ctx.font = "25px sans-serif";
ctx.fillText("Circle!", 265, 100);
}
We then draw the rectangle using its function. The button toggles drawing the circle and rectangle. Note how reset()
is called before drawing to clear the context.
drawRect();
let toggle = true;
const mybutton = document.getElementById("toggle-reset");
mybutton.addEventListener("click", () => {
ctx.reset();
if (toggle) {
drawCircle();
} else {
drawRect();
}
toggle = !toggle;
});
The result looks like this: