2011-10-24 116 views
0

我試圖在畫布上製作一個移動對象,但每次設置的時間間隔結束時,它都會給我提示錯誤:「更新未定義」,即使在init之前更新的定義正確。如何獲得設置間隔以正確調用更新?更新沒有定義?

<!doctype html> 
<html lang="en"> 
    <head> 
      <meta charset="utf-8"> 
      <title>Test</title> 
      <meta name="description" content="An HTML5 Test"> 
      <meta name="author" content="William Starkovich"> 
      <link rel="stylesheet" href="css/styles.css?v=1.0"> 
      <script type="text/javascript" src="jquery.js"></script> 
     <script type="text/javascript"> 
      $(document).ready(function(){ 

       var angle = 0.0; 
       var increment = 0.1; 

       function incrementAngle(angle, increment){ 
        angle += increment; 

        if(angle > Math.PI * 2) 
         angle -= (Math.PI * 2); 
       } 

       function update(angle, increment){ 
        incrementAngle(angle, increment); 

        //get a reference to the canvas 
        var ctx = $('#canvas')[0].getContext("2d"); 
        //draw a circle 
        ctx.strokeStyle = "#000000"; 
        ctx.beginPath(); 
        ctx.arc(20, 20, 15, angle, angle + Math.PI, true); 
        ctx.lineWidth = 5; 
        ctx.stroke(); 
        ctx.closePath(); 
       } 

       function init(angle, increment){ 
        update(angle, increment) 
        setInterval("update(angle, increment)",1000); 
       } 

       init(angle, increment); 

      }); 
      </script>  
    </head> 
    <body> 
     <canvas id="canvas" width="800px" height="100px"> 
     <p>Your browser doesn't support canvas.</p> 
     </canvas> 
    </body> 
</html> 

回答

2

您似乎希望使用全局變量,那麼爲什麼不走一路?

http://jsfiddle.net/mblase75/8L62c/3/

var angle = 0.0; 
var increment = 0.1; 

function incrementAngle() { 
    angle += increment; 
    if (angle > Math.PI * 2) angle -= (Math.PI * 2); 
} 

function update() { 
    incrementAngle(); 

    //get a reference to the canvas 
    var ctx = $('#canvas')[0].getContext("2d"); 
    //draw a circle 
    ctx.strokeStyle = "#000000"; 
    ctx.beginPath(); 
    ctx.arc(20, 20, 15, angle, angle + Math.PI, true); 
    ctx.lineWidth = 5; 
    ctx.stroke(); 
    ctx.closePath(); 
} 

function init() { 
    update(); 
    setInterval(update, 1000); 
} 

$(document).ready(function() { 
    init(); 
}); 
1

,因爲它們在全球範圍內執行,你的函數在處理的document.ready定義不要在eval使用字符串。如果你想提供的參數可以使用匿名函數:

setInterval(function() { update(angle, increment); } ,1000); 
+0

這會不會繼續傳遞相同的角度和增量'update'一遍又一遍? – Blazemonger

+0

@ mblase75不,它不會。它每次都會調用匿名函數,因爲它傳遞了一個變量的值,如果這些變量改變了它將傳遞的值,它將會改變。 – HoLyVieR

+0

有兩個問題 - 「更新」的範圍和變量的範圍。通過將'eval'ed代碼改爲閉包來解決'update'範圍問題。用mblase75的解決方案解決了變量範圍問題,該解決方案從函數簽名中刪除參數。 OP只改變全局變量的本地副本,而不是全局變量本身。 – Dennis