Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
How do I clear the current canvas in Javascript?

So in my Javascript code I want to keep a few buttons and when I click on them either a medium, large or small circle will appera and for this I need to clear the canvas before adding a new circle. For example I have made a medium circle and I want to make a small one, for this I need to clear the medium circle before so that I can make the small circle or else it will overlap. The canvas should be cleared when I click on the button. clearRect() doesnt work properly it removes the buttons too idk what's the issue. Please help :)

function Circle(r){
    let canvas = document.getElementById("MyCanvas");
    let ctx = canvas.getContext("2d");
    // the line below fixes the issue (not part of OP's question)
    // ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(350, 160, r, 0, 2 * Math.PI);
    ctx.strokeStyle = "#FF0000";
    ctx.fillStyle = fillcolor;
    ctx.stroke();
    ctx.fill();
    }
    
    var fillcolor = 'green'
    
    
    //large = 140
    //med = 100
    //small = 70
    
    var btn_med = document.createElement("button");
    btn_med.innerHTML = "Submit";
    btn_med.type = "submit";
    btn_med.name = "btn_med";
    btn_med.innerText = "Medium";
    
    btn_med.onclick = () => Circle(100);
    
    
    var btn_small = document.createElement("button");
    btn_small.innerHTML = "Submit";
    btn_small.type = "submit";
    btn_small.name = "btn_small";
    btn_small.innerText = "Small";
    
    btn_small.onclick = () => Circle(70);
    
    
    var btn_large = document.createElement("button");
    btn_large.innerHTML = "Submit";
    btn_large.type = "submit";
    btn_large.name = "btn_large";
    btn_large.innerText = "Large";
    
    btn_large.onclick = () => Circle(140);
    
    
    
    
    document.body.appendChild(btn_med);
    document.body.appendChild(btn_small);
    document.body.appendChild(btn_large);
<div id="outer">
<canvas id="MyCanvas" />
</div>

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!