#toggle-reset {
display: block;
}CanvasRenderingContext2D: reset() method / notebook
CanvasRenderingContext2D: reset() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
<button id="toggle-reset">Toggle</button>
<canvas id="my-house" width="500" height="200"></canvas>// Get the 2d context
const canvas = document.getElementById("my-house");
const ctx = canvas.getContext("2d");
function drawRect() {
// Set line width
ctx.lineWidth = 10;
// Stroke rect outline
ctx.strokeRect(50, 50, 150, 100);
// Create filled text
ctx.font = "50px serif";
ctx.fillText("Rect!", 70, 110);
}
function drawCircle() {
// Set line width
ctx.lineWidth = 5;
// Stroke out circle
ctx.beginPath();
ctx.arc(300, 100, 50, 0, 2 * Math.PI);
ctx.stroke();
// Create filled text
ctx.font = "25px sans-serif";
ctx.fillText("Circle!", 265, 100);
}drawRect();
// Toggle between circle and rectangle using button
let toggle = true;
const myButton = document.getElementById("toggle-reset");
myButton.addEventListener("click", () => {
ctx.reset(); // Clear the context!
if (toggle) {
drawCircle();
} else {
drawRect();
}
toggle = !toggle;
});