2014-12-18 52 views
0

這是我的代碼:canvas.getContext(「2D」)不起作用

<!DOCTYPE html> 
<html> 
    <head> 
     <link href="style.css" rel="stylesheet" type="text/css" /> 
     <script type="text/javascript"> 
      (function drawCanvas(){ 
       var canv = document.getElementById('testcanvas1'); 

       if(canv.getContext){ 
        alert("test"); 
        var context = doof.getContext('2d'); 

        context.fillStyle = "rgb(255, 0, 255)"; 
        context.fillRect(0, 0, canvas.width, canvas.height); 
       } 
      })(); 
     </script> 
    </head> 
    <body> 
     <canvas id="testcanvas1"></canvas> 
    </body> 
</html> 

毫無警覺,所以我假設變量canv.getContext是假的。爲什麼?總的來說.getContext('2d')不適用於我的firefox 34.我如何使這個功能工作?

+0

'canv'爲'null',因爲'#testcanvas1'尚未加載。因此,'canv.getContext'會引發錯誤。 – Oriol

回答

0

您正在加載文檔之前執行您的代碼。解決方案:

window.onload = function() { 
    (function drawCanvas(){ 
     var canv = document.getElementById('testcanvas1'); 

     if(canv.getContext){ 
      alert("test"); 
      var context = doof.getContext('2d'); 

      context.fillStyle = "rgb(255, 0, 255)"; 
      context.fillRect(0, 0, canvas.width, canvas.height); 
     } 
    })(); 
}