2012-12-09 50 views
0

我試圖將圖像添加到我的畫布,但它似乎沒有工作,我已經採取一看,也看不出什麼毛病我的代碼,但也許別人可以。將圖像添加到一個HTML5畫布

這是我的JS文件。

if (window.addEventListener) 
{ 
    window.addEventListener('load', onLoad, false); 
} 

function onLoad() 
{ 
var canvas; 
var context; 

function initialise() 
{ 
    canvas = document.getElementById('canvas'); 

    if (!canvas.getContext) 
    { 
     alert('Error: no canvas.getContext!'); 
     return; 
    } 

    context = canvas.getContext('2d'); 
    if (!context) 
    { 
     alert('Error: failed to getContext!'); 
     return; 
    } 

} 
} 

function draw() 
{ 
    var sun = new Image(); 
    sun.src = 'images.sun.png'; 
    context.drawImage(sun, 100, 100); 
} 

onLoad(); 
draw(); 

這裏是我的HTML mabye這將有助於發現問題

<!doctype html> 
    <html> 
     <head> 
      <title>Test</title> <script type="text/javascript" src="javascript/canvas.js"></script> 
     </head> 
     <body> 
      <canvas id="canvas" width="800" height="600"> 
       Your browser does not support the canvas tag 
      </canvas> 

     </body> 
    </html> 

回答

1

的問題是,您在聲明帆布&背景的onLoad(),但嘗試訪問它的draw()。

這樣,通過使它們成爲全球性的問題就解決了:

var canvas; 
var context; 

if (window.addEventListener) { 
    window.addEventListener('load', function(){ 
     onLoad(); 
    }, false); 
} 

function onLoad() { 
    initialise(); 
    draw(); 
} 

function initialise() { 
    canvas = document.getElementById('canvas'); 

    if (!canvas.getContext) { 
     alert('Error: no canvas.getContext!'); 
     return; 
    } 

    context = canvas.getContext('2d'); 
    if (!context) { 
     alert('Error: failed to getContext!'); 
     return; 
    } 

} 

function draw() { 
    var sun = new Image(); 
    sun.addEventListener('load', function(){ 
     context.drawImage(sun, 100, 100); 
    }, false); 
    sun.src = 'http://puu.sh/1yKaY'; 
} 
+0

法「的drawImage」我得到相同錯誤遺漏的類型錯誤:無法調用未定義 –

+0

法「的drawImage」現在它應該爲你工作。 – andy

+0

感謝您嘗試,但仍然得到錯誤 –

0

嘗試繪製圖像,它的onload事件

sun.onload = function() { 
    context.drawImage(sun, 100, 100); 
}; 
+0

時,我想這鉻調試遊戲我這個錯誤 遺漏的類型錯誤:無法調用未定義 –

相關問題