I want to clear the canvas and then draw new shape on click of same button at once. "Draw shape" is the button I am using which draws shape of given parameters. Now when again I select some other shape without reloading the page, and click on the button again, it should clear existing shape and show only new one. But it is overwriting new shape over existing shape. Can somebody specify what wrong i am doing?
Code:
<!DOCTYPE html>
<html>
<title>Blue Orchids School</title>
<head align="centre"><b>Blue Orchids School</b></head>
<body>
<button onclick="draw()" type="submit">Draw shape</button><br><br>
<canvas id="myCanvas" width="600" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p id="details"></p>
<script>
function draw() {
rendershape("Circle", 4, 22, 5, "Red")
rendershape("Circle", 4, 220, 5, "Red")
}
function rendershape(shape, width, xcoordinate, ycoordinate, colour)
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.clearRect(0,0,c.width,c.height);
//To draw a circle
if(shape=='Circle'||shape=='circle')
{
ctx.lineWidth=width;
ctx.arc(xcoordinate,ycoordinate,50,0,2*Math.PI);
ctx.fillStyle= colour;
ctx.fill();
ctx.stroke();
}
document.getElementById("details").innerHTML += 'Shape: ' + shape + '<br>' + 'Colour : '+ colour + '<br>' +' X-coordinate: '+ xcoordinate + '<br>' +' Y-coordinate: '+ ycoordinate + '<br>' + ' Width: '+ width;
}
</script>
</body>
</html>