JavaScript clearRect function doesn't work

I’m a beginner in HTML and JavaScript and I made a simple canvas that draws a red square when a user presses the mouse button. But when I press the clear canvas button nothing happens. and I don’t know what is wrong with the code.

I tried putting the code in a separate file, but that didn’t work. I have no idea what to do

Here’s my Code:

const canvas = document.getElementById("myCanvas")
const ctx = canvas.getContext('2d')
canvas.style.border = "1px solid black"

canvas.onmousedown = function(event) {
  ctx.beginPath();
  let x = event.x
  let y = event.y
  ctx.fillStyle = "red"
  ctx.fillRect(x - 28.5, y - 28.5, 20, 20)
  ctx.stroke()
  ctx.closePath();
  console.log("click")


}

function clear() {
  console.log("clear")
  ctx.clearRect(0, 0, canvas.width, canvas.height)
}
<canvas id="myCanvas" width="500" height="500"></canvas><br>
<button type="button" onclick="clear()">Clear Canvas</button>

>Solution :

As @imvain2 pointed out in comments, this is an issue with the function name. It works when you rename it to a non-reserved word:

const canvas = document.getElementById("myCanvas")
const ctx = canvas.getContext('2d')
canvas.style.border = "1px solid black"

canvas.onmousedown = function(event) {
  ctx.beginPath();
  let x = event.x
  let y = event.y
  ctx.fillStyle = "red"
  ctx.fillRect(x - 28.5, y - 28.5, 20, 20)
  ctx.stroke()
  ctx.closePath();
  console.log("click")


}

function clearcanvas() {
  console.log("clear")
  ctx.clearRect(0, 0, canvas.width, canvas.height)
}
<canvas id="myCanvas" width="500" height="500"></canvas><br>
<button type="button" onclick="clearcanvas()">Clear Canvas</button>

Leave a Reply