本文介绍了getImageData()返回全零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试输出图像中的像素值。图像正确加载;这里的另一个答案表明,浏览器试图在图像加载完成之前读取像素,但是我可以看到它在alert()触发时被加载。

I'm trying to output the pixel values from an image. The image is loading correctly; another answer on here suggested that the browswer is trying to read the pixels before the image is finished loading, but I can see that it's loaded by the time the alert() fires.

function initContext(canvasID, contextType)
{
   var canvas = document.getElementById(canvasID);
   var context = canvas.getContext(contextType);
   return context;
}

function loadImage(imageSource, context)
{
    var imageObj = new Image();
    imageObj.onload = function()
    {
        context.drawImage(imageObj, 0, 0);
    };
    imageObj.src = imageSource;
    return imageObj;
}

function readImage(imageData)
{
    console.log();
    console.log(imageData.data[0]);
}

var context = initContext('canvas','2d');
var imageObj = loadImage('images/color-test.png',context);
var imageData = context.getImageData(0,0,10,10);
alert();
readImage(imageData);


推荐答案

Image.onload()加载图像时,异步调用。在当前代码调用 context.getImageData()之后,可能会发生这种情况。

Image.onload() is called asynchronously when the image has been loaded. That can happen after your current code calls context.getImageData().

以下代码应该有效:

function initContext(canvasID, contextType)
{
   var canvas = document.getElementById(canvasID);
   var context = canvas.getContext(contextType);
   return context;
}

function loadImage(imageSource, context)
{
    var imageObj = new Image();
    imageObj.onload = function()
    {
        context.drawImage(imageObj, 0, 0);
        var imageData = context.getImageData(0,0,10,10);
        readImage(imageData);
    };
    imageObj.src = imageSource;
    return imageObj;
}

function readImage(imageData)
{
    console.log();
    console.log(imageData.data[0]);
}

var context = initContext('canvas','2d');
var imageObj = loadImage('images/color-test.png',context);

如果要访问 imageData 值在 loadImage()之外,你有2个基本选择:

If you want to access the imageData value outside of loadImage(), you have 2 basic choices:


  1. 存储 imageData 在函数外声明的变量中。在这种情况下,在调用 onload()之前,将取消设置该值,因此外部代码必须在调用 readImage之前测试它是否合理(imageData)

  2. 让外部代码注册一个回调函数,然后让你的 onload()使用 imageData 值调用该函数。

  1. Store the imageData in a variable that is declared outside the function. In this case, the value will be unset until your onload() is called, so the outside code would have to test it for reasonableness before calling readImage(imageData).
  2. Have the outside code register a callback function, and have your onload() call that function with the imageData value.

这篇关于getImageData()返回全零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:29