簡體   English   中英

當我清除畫布時,“ canvas.clearRect不是函數”

[英]“canvas.clearRect is not a function” when I clear the canvas

我正在嘗試在HTML5畫布上繪制一個圓並四處移動。

我寫了這個Javascript代碼:

 var a = 0; function draw() { var c = document.getElementById("game"); var ctx = c.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(45+a, 45, 40, 0, 2 * Math.PI); ctx.stroke(); a++; } var t=setInterval(draw,1000); 
 <canvas id="game" width="640" height="480"></canvas> 

當我嘗試執行它時,在控制台中出現此錯誤:

TypeError:canvas.clearRect不是函數

我該如何解決?

謝謝。

clearRect方法中,因為canvasundefinedcanvas.widthcanvas.height將引發錯誤。 您應該傳遞有效的對象。

 var a = 0; function draw() { var canvas = document.getElementById("game"); var ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(45 + a, 45, 40, 0, 2 * Math.PI); ctx.stroke(); a++; } var t = setInterval(draw, 1000); 
 <canvas id="game" width="640" height="480"></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM