javascript Javascript从URL将动态图像绘制到canvas元素上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10282824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript draw dynamic image from URL onto canvas element
提问by EffTerrible
I am attempting to draw a dynamic PNG image (one that is generated by a PHP script) onto a Canvas element using its URL. I can't really post exact URLs for pages I'm testing this out on, as you must be logged in to the website.
我正在尝试使用其 URL 将动态 PNG 图像(由 PHP 脚本生成的图像)绘制到 Canvas 元素上。我真的无法发布我正在测试的页面的确切 URL,因为您必须登录到该网站。
An example of one of the dynamic image URL I'm using is: http://www.website.com/includes/dynamicimage.php?ID=29718958161
我正在使用的动态图像 URL 之一的示例是:http: //www.website.com/includes/dynamicimage.php?ID=29718958161
If you were logged into this particular website and pasted that URL into your address bar, it would correctly display the image. However, the following Javascript code is not properly drawing it onto the canvas element:
如果您登录到该特定网站并将该 URL 粘贴到您的地址栏中,它将正确显示图像。但是,以下 Javascript 代码没有正确地将其绘制到 canvas 元素上:
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;
}
I'm having two pop-up windows display both the dynamic image and what is drawn to the canvas, but the canvas is always blank. I am then attempting to do further RGB testing on the image after setting the "pix" variable, but since the image is never drawn to the canvas element, this step fails.
我有两个弹出窗口显示动态图像和画布上绘制的内容,但画布始终是空白的。然后,我尝试在设置“pix”变量后对图像进行进一步的 RGB 测试,但由于图像从未绘制到画布元素,因此此步骤失败。
回答by Phrogz
Your problem is that you are not waiting for the image to load before attempting to draw it to the canvas. See the section titled "Playing It Safe"in this questionfor more details.
您的问题是在尝试将其绘制到画布之前,您没有等待图像加载。请参见标题为“谨慎行事”在这个问题的更多细节。
In short:
简而言之:
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.