Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading