2012-04-23 91 views
6

我正在嘗試使用其網址將動態PNG圖像(由PHP腳本生成的圖像)​​繪製到Canvas元素上。我無法爲我正在測試的網頁發佈確切的網址,因爲您必須登錄網站。Javascript將動態圖像從URL繪製到畫布元素

我使用的是動態圖像URL的一個的一個例子是:http://www.website.com/includes/dynamicimage.php?ID=29718958161

如果你登錄到該特定網站,並粘貼該URL地址欄中,它會正確顯示圖像。但是,下面的JavaScript代碼不正確繪製它在畫布上的元素:

function checkImage(imageContext) { 
    var canvas = document.createElementNS(
     'http://www.w3.org/1999/xhtml', 'canvas'); 
    canvas.width = imageContext.width; 
    canvas.height = imageContext.height; 

    var context = canvas.getContext("2d"); 
    var img = new Image(); 
    img.src = imageContext.src; 
    context.drawImage(img, 0, 0); 

    newWindow = window.open(imageContext.src, 'newWin', 'width=300,height=300'); 
    newWindow2 = window.open('', 'newWin2', 'width=300,height=300'); 
    newWindow2.document.body.appendChild(canvas); 

    var imgd = context.getImageData(0, 0, imageContext.width, 
     imageContext.height); 
    var pix = imgd.data; 
} 

我有兩個彈出式窗口同時顯示動態圖像,什麼是畫在畫布上,但畫布始終是空白。在設置「pix」變量後,我試圖對圖像進行進一步的RGB測試,但由於圖像從未繪製到畫布元素,因此此步驟失敗。

回答

13

你的問題是,你是不是等待圖像試圖把它拖到畫布前加載。看到標題爲「謹慎行事」this question瞭解更多詳情。

簡而言之:

var img = new Image;  // First create the image... 
img.onload = function(){ // ...then set the onload handler... 
    ctx.drawImage(img,0,0); 
}; 
img.src = "someurl";  // *then* set the .src and start it loading. 
+0

感謝您的快速反應和解釋!你的建議非常完美! :) – EffTerrible 2012-04-23 19:50:41