2009-05-12 2 views
0

그래, Firefox가 $ ("# canvas") [0] .getContext ('2d'); 정의되지 않았습니다. 나는 모든 함수가 그것에 접근 할 수 있도록 함수에서 제외했다. 그러나 여기서 ctx는 여전히 정의되지 않았다. I는 이름 기능 CTX의 위치를 ​​전송할 때jQuery- 제발 내게 설명해주세요. 클로저, 변수 컨텍스트

(function($) { 
     // Undefined 
     var ctx = $('#canvas')[0].getContext("2d"); 
     var x = 150; 
     var y = 150; 
     var dx = 2; 
     var dy = 4; 
     $(function() { 
      setInterval(draw, 10); 
     }) 
     function draw() { 
      ctx.clearRect(0,0,300,300); 
      ctx.beginPath(); 
      ctx.arc(x,y,10,0,Math.PI*2,true); 
      ctx.closePath(); 
      ctx.fill(); 
      x+=dx; 
      y+=dy; 
     } 
    })(jQuery); 

는하지만, CTX는 정의되지 않는다 :

(function($) { 
     var ctx; 
     var x = 150; 
     var y = 150; 
     var dx = 2; 
     var dy = 4; 
     $(function() { 
       //Not Undefined 
      ctx = $("#canvas")[0].getContext('2d'); 
      setInterval(draw, 10); 
     }) 
     function draw() { 
      ctx.clearRect(0,0,300,300); 
      ctx.beginPath(); 
      ctx.arc(x,y,10,0,Math.PI*2,true); 
      ctx.closePath(); 
      ctx.fill(); 
      x+=dx; 
      y+=dy; 
     } 
    })(jQuery); 

무엇이 잘못 첫번째 코드? var ctx가 맨 위에 선언되어 있음을 의미합니다. 그러면 글로벌 변수가됩니다. 흠, 내가 가진 오류는 $ ("# canvas") [0]은 정의되지 않았습니다. #canvas에 액세스 할 수 없다는 의미입니다. 왜 그렇습니까?

답변

3

첫 번째 호출에서 실제로 DOM을로드 한 후에 만 ​​처리되는 Function 객체를 다른 컨텍스트에서 생성하기 때문입니다.

페이지의 모든 요소가 이미로드되었을 때 익명 함수가 호출되므로 호출자는 jQuery 핵심 함수이며 해당 컨텍스트는 여기에서 코딩하는 것과 완전히 다릅니다.

나는 $() 전화 내부의 모든 것을 포장 좋을 것, 그래서 이것은 작동합니다 :

(function($) { 
     $(function() { 
      var ctx = $("#canvas")[0].getContext('2d'); 
      var x = 150; 
      var y = 150; 
      var dx = 2; 
      var dy = 4; 

      setInterval(draw, 10); 

      function draw() { 
        ctx.clearRect(0,0,300,300); 
        ctx.beginPath(); 
        ctx.arc(x,y,10,0,Math.PI*2,true); 
        ctx.closePath(); 
        ctx.fill(); 
        x+=dx; 
        y+=dy; 
      } 
     }); 
})(jQuery); 
+0

올바른 것입니다. 첫 번째 것은 작동하지 않습니다. 왜냐하면 캔버스 객체를 얻으려고 할 때 아직 실제로로드되지 않았기 때문입니다. –

+0

콜백 내부에 코드를 래핑하는 것이 맞지만 컨텍스트 문제에 대해서는 * 잘못되었습니다. 문제는 아마 canvas 태그가 선언되기 전에 javascript 코드가 실행 중일 것입니다. 나는 이것을 나의 답에서 보여 주었다. – brianpeiris

+0

감사합니다. 나는이 방법이 작동하는 방식으로 실험하고 있었다. 나는 그것을 지금 이해한다. – rymn

4

을 당신이 문제를 착각 한 것 같아요. 변수 컨텍스트를 잘못 이해 한 것은 아니지만 을 실행하고 있고 캔버스 태그가 선언 된 것일 수 있습니다.

다음 코드는 문제를 보여줍니다. "canvasOne is undefined!"라는 메시지가 표시됩니다. 선언되기 전에 canvasOne에 액세스하려고하기 때문에 (<canvas> 태그의 위치에주의하십시오).

나는 데모 여기 호스팅 만든 : (http://jsbin.com/afuju/edit를 통해 편집) http://jsbin.com/afuju를 셉의 말씀

<html> 
    <head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    </head> 
    <body> 
    <script> 
     /* 
     The following line of code is run as soon as the browser sees it. 
     Since the "canvasOne" tag is not declared yet, the variable will be undefined. 
     */ 
     var canvasOne = $('#canvasOne')[0]; 

     $(function() { 
     // The following code is run after the whole document has finished loading. 
     if (canvasOne === undefined) { 
      alert('canvasOne is undefined!'); 
     } 
     else { 
      canvasOne.getContext("2d").fillRect(5, 5, 15, 15); 
     } 
     }); 
    </script> 
    <canvas id="canvasOne"></canvas> 



    <canvas id="canvasTwo"></canvas> 

    <script> 
     /* 
     The following line of code is run as soon as the browser sees it. 
     But since the "canvasTwo" tag *is* declared above, the variable will *not* be undefined. 
     */ 
     var canvasTwo = $('#canvasTwo')[0]; 

     $(function() { 
     // The following code is run after the whole document has finished loading. 
     if (canvasTwo === undefined) { 
      alert('canvasTwo is undefined!'); 
     } 
     else { 
      canvasTwo.getContext("2d").fillRect(5, 5, 15, 15); 
     } 
     }); 
    </script> 



    <script> 
     $(function() { 
     /* 
      The following code is run after the whole document has finished loading. 
      Hence, the variable will *not* be undefined even though the "canvasThree" tag appears after the code. 
     */ 
     var canvasThree = $('#canvasThree')[0]; 
     if (canvasThree === undefined) { 
      alert('canvasThree is undefined!'); 
     } 
     else { 
      canvasThree.getContext("2d").fillRect(5, 5, 15, 15); 
     } 
     }); 
    </script> 

    <canvas id="canvasThree"></canvas> 
    </body> 
</html> 
+0

감사합니다 Brian Peiris! – rymn

+0

+1 데모 배포 – Seb