2012-03-04 103 views
0

我試圖借鑑HTML畫布圖像:帆布的drawImage不工作

var mainCanvas = document.getElementById('mainCanvas'); 
var ctx = mainCanvas.getContext('2d'); 

我做一個Ajax請求,並解析,我從它那裏得到(完美的作品)的XML數據,後來當我畫它在畫布上的不同形狀也是100%。 什麼不工作是一個圖像在下面的代碼繪製:

$(data).find('Object').each(function(){ 
    type = $(this).attr('type'); 
    x = $(this).attr('X'); 
    y = $(this).attr('Y'); 
    switch(type){ 
    case '2': 
    height = h_panel; 
    width = w_panel; 
    ctx.fillStyle = sColor; 
    ctx.fillRect(x,y,width,height); 
    break; 
    case '1': 
    var powerFactoryImg = new Image(); 
    powerFactoryImg.onload = function(){ 
     alert('test'); 
     ctx.drawImage(powerFactoryImg,x,y,90,80); 
    }; 
    powerFactoryImg.src = 'images/power_factory.png'; 
    break; 

    //Other cases go here - they draw rectangles - all of them work 

    } 
}); 

我有Chrome開發者工具的形象是加載檢查;此外,正在調用.onload中的警報。該代碼在Chrome和FF中都不起作用。 這裏可能是什麼問題?

謝謝

+0

鑑於正在加載圖像,問題可能出在其他地方,而不是您提供的代碼中,或者您在畫布邊界外繪製圖像,因此看不到它。或者可能畫一些東西呢? – Delta 2012-03-04 19:01:44

+1

檢查onload中x和y的值:alert('test:'+ x +','+ y); – 2012-03-04 19:06:33

回答

3

該缺陷可能是由你的任務沒有var造成的。在循環中,您不斷覆蓋type,xy變量。前綴var解決您的問題。

參見:What is the purpose of the var keyword and when to use it (or omit it)?

$(data).find('Object').each(function(){ 
    var type = $(this).attr('type');//<-- var 
    var x = $(this).attr('X');  //<-- var 
    var y = $(this).attr('Y');  //<-- var 
    switch(type){ 
    case '2': 
     var height = h_panel; // <-- var 
     var width = w_panel; // <-- var 
     ctx.fillStyle = sColor; 
     ctx.fillRect(x,y,width,height); 
    break; 
    case '1': 
     var powerFactoryImg = new Image(); 
     powerFactoryImg.onload = function(){ 
      alert('test: ' + [x, y]); //<-- "test" is not very useful. Add [x,y] 
      ctx.drawImage(powerFactoryImg,x,y,90,80); 
     }; 
     powerFactoryImg.src = 'images/power_factory.png'; 
    break; 

    //Other cases go here - they draw rectangles - all of them work 

    } 
}); 

PS:爲了調試的目的,我建議使用console.log超過alert

+0

這工作得很好,非常感謝! X和Y之前未定義。但我仍然很難理解覆蓋如何導致這種情況。如果X和Y值是全局的,並且被多次覆蓋,爲什麼它們不能被正確讀取,並且在讀取時結束爲未定義? – ZenJ 2012-03-05 19:19:30

+1

@doktor'.onload'事件偵聽器被延遲,並在圖像加載時執行。在加載第一個圖像之前,'.each'循環已經完成,導致最近的(全局?)'x'和'y'變量等於最新的'x'和'y'屬性。所以,只繪製一條線。因此,你認爲「沒有」會發生,而實際上,同一條線是多次繪製的。本地聲明變量解決了這個問題,因爲每個'onload'處理程序將正確地解析'x'和'y'。 – 2012-03-05 20:05:09

+0

很好解釋,非常感謝! – ZenJ 2012-03-05 22:09:43