2012-04-23 90 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