How To Clear An HTML5 Canvas

JavaScript

05/06/2021


How do you clear an entire canvas of its drawings? For that, there's a context method called clearRect. Let me show you:

JAVASCRIPT
const context = canvas.getContext('2d')
context.clearRect(0, 0, canvas.width, canvas.height)

clearRect takes in 4 arguments:

  • The 1st two are the x and y coordinates, respectively. Above, we specified the origin of the canvas, i.e. the top-left corner.
  • The last 2 are width and height, respectively, which start from said coordinates. Here, canvas represents the canvas element.

Given those 4 parameters, anything inside those dimensions are removed from the canvas.

Trigger with button

Most drawing apps will implement this exact functionality using some sort of reset button. To mimic this, start off by wrapping clearRect in a function.

JAVASCRIPT
const resetCanvas = () => context.clearRect(0, 0, canvas.width, canvas.height)

Then simply attach it to a button's onclick event.

HTML
<button onclick='resetCanvas()'>Reset</button>

A working version of this can be found in my Codepen.


WRITTEN BY

Code and stuff