Javascript将URL中的动态图像绘制到canvas元素上 [英] Javascript draw dynamic image from URL onto canvas element

查看:1019
本文介绍了Javascript将URL中的动态图像绘制到canvas元素上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用其URL将动态PNG图像(由PHP脚本生成的图像)​​绘制到Canvas元素上。我无法为我正在测试的网页发布确切的网址,因为您必须登录网站。

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.

其中一个动态示例我正在使用的图片网址是: http://www.website.com/includes /dynamicimage.php?ID=29718958161

An example of one of the dynamic image URL I'm using is: http://www.website.com/includes/dynamicimage.php?ID=29718958161

如果您已登录此特定网站并将该网址粘贴到地址栏中,则会正确显示该图片。但是,以下Javascript代码未正确地将其绘制到canvas元素上:

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:

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测试,但由于图像从未被绘制到canvas元素,因此该步骤失败。

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.

推荐答案

您的问题是,在尝试将图像绘制到画布之前,您不是在等待图像加载。请参阅 安全播放 的部分-to-dataurl-be-available-immediately>这个问题了解更多细节。

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 question for more details.

简而言之:

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.

这篇关于Javascript将URL中的动态图像绘制到canvas元素上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆