1

我目前正在做一个项目,为此我需要使用画布的像素。我确实使用 canvascontext.getImageData(0,0,width,height).data() 提取像素。这段代码运行良好,并返回一个像素数组。在这个数组中,像素的位置如下:[r1,g1,b1,a1,r2,g2,b2,a2...]。现在我在 Java 中使用了一个类似的数组,但是这里返回的像素是这样的: [r1,r2,g1,g2,b1,b2,a1,a2] 这使得使用掩码获取值成为可能. 由于在 JS 中有所不同,我使用以下函数从数组中提取值并在编辑后设置它们:

 ImageClass.prototype.getRed = function(temp){
   return imageData.pixels[temp];
 }

 ImageClass.prototype.setRed = function(r, temp){
   imageData.pixels[temp] = r;
 }

 ImageClass.prototype.getGreen = function(temp){
   return imageData.pixels[Number(temp)+1];
 }

 ImageClass.prototype.setGreen = function(g, temp){
   imageData.pixels[Number(temp)+1] = g;
 }

 ImageClass.prototype.getBlue = function(temp){
   return imageData.pixels[Number(temp)+2];
 }

 ImageClass.prototype.setBlue = function(b, temp){
   imageData.pixels[Number(temp)+2] = b;
 }

 ImageClass.prototype.getAlpha = function(temp){
   return imageData.pixels[Number(temp)+3];
 }

 ImageClass.prototype.setAlpha = function(a, temp){
   imageData.pixels[Number(temp)+3] = a;
 }

temp 是一个表示索引的整数值。现在我的问题:虽然以下功能(红色)有效,但下一个功能(绿色)不起作用。我不知道为什么以及如何开始调试。

ImageClass.prototype.red = function(){
  this.getPixels();
  for (index = 0; index < imageData.pixelsLength; index += 4) {
    var g = this.getGreen(index);
    var b = this.getBlue(index);

    g = 0;
    b = 0;

    this.setGreen(g, index);
    this.setBlue(b, index);

  }
  this.draw();
}

ImageClass.prototype.green = function(){
  this.getPixels();
  for (index = 0; index < imageData.pixelsLength; index += 4) {
    var r = this.getRed(index);
    var b = this.getBlue(index);

    r = 0;
    b = 0;

    this.setRed(r, index);
    this.setBlue(b, index); 
  }
  this.draw();
}

getPixels() 函数只是使像素数组全局可用(在命名空间中)。draw-function 的功能与名称所说的完全一样。

如果有人知道从数组中提取像素的更简单方法,以便我可以访问所有红色、所有绿色等。我愿意接受建议。

提前致谢。

4

1 回答 1

0

您可以删除对 getGreen 和 getBlue 的调用,因为无论如何您只是覆盖它们。

轻微修改

ImageClass.prototype.red = function(){
  this.getPixels();
  for (index = 0; index < imageData.pixelsLength; index += 4) {
    var g = 0, b = 0;

    this.setGreen(g, index);
    this.setBlue(b, index);

  }
  this.draw();
}

避免ImageClass.prototype.getRed等。

如果你想要一个非常简单的方法,你可以这样做:

offsets {r: 0, g: 1, b: 2, a: 3}

ImageClass.prototype.red = function(){
  this.getPixels();
  for (index = 0; index < imageData.pixelsLength; index += 4) {
      imageData.pixels[index+offsets.g] = 0;
      imageData.pixels[index+offsets.b] = 0;
  }
  this.draw();
}

简单而完整的替代方案

您可以通过生成这些函数来避免重复代码。

offsets {r: 0, g: 1, b: 2, a: 3}

function MakeColorFunction(omit1, omit2){
  return (function(){
    this.getPixels();
    for (index = 0; index < imageData.pixelsLength; index += 4) {
      imageData.pixels[index+offsets[omit1]] = 0;
      imageData.pixels[index+offsets[omit2]] = 0;
    }
    this.draw();
  });
}

ImageClass.prototype.red = MakeColorFunction("g", "b");
ImageClass.prototype.green = MakeColorFunction("b", "r");
ImageClass.prototype.blue = MakeColorFunction("r", "g");
于 2013-08-06T09:55:50.517 回答