像素RGB值全为零 [英] Pixel RGB values are all zero

查看:637
本文介绍了像素RGB值全为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历画布的像素并将其颜色设为RGB,但是即使画布上有图像,所有像素也具有0、0、0 RGB值。

I want to iterate through pixels of canvas and get their colors as RGB but all pixels have 0,0,0 RGB value even though there is an image on canvas.

这是我的代码; (我的测试图像在jsfiddle中看不到)

Here is my code; (my test image is not seen in jsfiddle)

http ://jsfiddle.net/mwPfa/2/

for(i = 400; i < 1000; i += 4) {
      red = imageData.data[i];
      green = imageData.data[i + 1];
      blue = imageData.data[i + 2];
      alpha = imageData.data[i + 3];
      console.log(red + "," + green + "," + blue + "," + alpha);
    }


推荐答案

工作示例- http://jsfiddle.net/mwPfa/3/

这些要提的东西很少:


  1. window.onload-在jsfiddle中,您不需要使用它。

  2. 由于使用CORS,如果要在jsfiddle中从外部域加载图像,则必须使用支持该图像的图像并通过 img.crossOrigin = Anonymous; -并不是每个图像都可以在这里工作。

  3. 如果您要访问图像数据-您必须等到图像加载后才能绘制图像并仅在加载时访问数据处理程序。您不希望在加载图像之前访问画布数据...有时它可以工作,但是您想要一个稳定的代码,它可以在任何地方都可以工作,不是吗?

  4. RGB值为0, 0,0表示有效黑色,因此请确保您未测试左上角为黑色的图像。

  1. window.onload - in jsfiddle you dont need to use it.
  2. becouse of CORS, if you want to load image form external domain in jsfiddle, you have to use image that supports it and load in with img.crossOrigin = "Anonymous"; - not every image will work here.
  3. if you want to access image data - you HAVE to wait until image is loaded, so draw image and access the data only in onload handler. You dont want to access canvas data before image was loaded... It works sometimes, but you want stable code, that works everytime everwhere, don't you?
  4. RGB with values 0,0,0 means valid black color, so make sure you don't test image with black top-left corner.

这篇关于像素RGB值全为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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