Javascript 将动态图像从 URL 绘制到 Canvas 元素上

标签 javascript image canvas

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

我正在使用的动态图像 URL 之一的示例是:http://www.website.com/includes/dynamicimage.php?ID=29718958161

如果您登录到这个特定网站并将该 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;
}

我有两个弹出窗口显示动态图像和绘制到 Canvas 上的内容,但 Canvas 始终是空白的。然后我尝试在设置“pix”变量后对图像进行进一步的 RGB 测试,但由于图像从未绘制到 Canvas 元素,因此此步骤失败。

最佳答案

您的问题是您在尝试将图像绘制到 Canvas 之前没有等待图像加载。请参阅 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.

关于Javascript 将动态图像从 URL 绘制到 Canvas 元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10282824/

相关文章:

javascript - jQuery - jScrollPane 不显示滚动条

css悬停不执行

java - Android 相机预览 byte[] 到 Java 图片

javascript - 使 firefox 刷新图像更快

javascript - Julia 集合的 JS canvas 实现

javascript - 使用 puppeteer 从另一个文件导入 javascript 函数?

javascript - object.create 和 new Object 的原型(prototype)区别

javascript - XML 解析错误 : no root element found

javascript - 在 Three.js 和 WebGL 中渲染 2D SVG 时遇到问题

javascript - Canvas + SVG 路径中的 Atan2 旋转卡顿