CanvasRenderingContext2D.clearRect()

The CanvasRenderingContext2D.clearRect() method of the Canvas 2D API sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content.

Syntax

void ctx.clearRect(x, y, width, height);

Parameters

x
The x axis of the coordinate for the rectangle starting point.
y
The y axis of the coordinate for the rectangle starting point.
width
The rectangle's width.
height
The rectangle's height.

Usage notes

A common problem with clearRect is that it may appear it does not work when not using paths properly. Don't forget to call beginPath() before starting to draw the new frame after calling clearRect.

Examples

Using the clearRect method

This is just a simple code snippet which uses the clearRect method.

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.lineTo(120, 120);
ctx.closePath(); // draws last line of the triangle
ctx.stroke();
ctx.clearRect(10, 10, 100, 100);
// clear the whole canvas
// ctx.clearRect(0, 0, canvas.width, canvas.height);

Edit the code below and see your changes update live in the canvas:

Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code" style="height:140px;">
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(200,20);
ctx.lineTo(120,120);
ctx.closePath(); // draws last line of the triangle
ctx.stroke();
ctx.clearRect(10, 10, 100, 100);</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;
function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}
reset.addEventListener("click", function() {
  textarea.value = code;
  drawCanvas();
});
edit.addEventListener("click", function() {
  textarea.focus();
})
textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'CanvasRenderingContext2D.clearRect' in that specification.
Living Standard  

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Document Tags and Contributors

 Contributors to this page: nmve, erikadoyle, Nickolay, fscholz
 Last updated by: nmve,