2016-04-08 19 views
1

我想清除畫布,然後一次點擊同一個按鈕畫出新形狀。 「繪製形狀」是我用來繪製給定參數形狀的按鈕。現在,當我再次選擇其他形狀而無需重新加載頁面時,再次單擊該按鈕時,它應該清除現有形狀並僅顯示新形狀。但它覆蓋了現有形狀的新形狀。有人可以指定我在做什麼錯嗎?context.clearRect(x,y,width,height)與單個按鈕一起使用時不起作用

代碼:

<!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>

+0

畫布DOM元素在哪裏?它看起來像你沒有包括你所有的HTML代碼。變量** c **,您抓取canvas元素,控制檯註銷正確嗎? – Shakespeare

+0

我已添加。雖然在此處複製粘貼代碼,但並未顯示出來,它應該是在「您的瀏覽器不支持HTML5畫布標記。」 「 」 「它是: 您的瀏覽器不支持HTML5 canvas標記。 是的,console.log顯示c變量 – Sarang

+0

[clearRect函數可能重複不會清除畫布](http://stackoverflow.com/questions/13435959/clearrect-function-doesnt-clear-the -canvas) – Nickolay

回答

0

看起來像一個錯字情況。

ctx.clearRect(0,0,c.widht,c.height); 

將其更改爲:

ctx.clearRect(0,0,c.width,c.height); 
+0

更正了錯字...仍然不能正常工作:( – Sarang