画布:屏蔽图像并保留其alpha通道?

时间:2012-01-27 10:40:26

标签: javascript html5 canvas html5-canvas

这是我正在尝试做的事情:

  1. 获取图像A和图像B.图像B是黑白掩模图像。
  2. 将图像A的Alpha通道替换为图像B的红色通道。
  3. 在画布上绘制图像C.
  4. 在图像C上绘制图像A.
  5. 在步骤4之前,一切似乎都没问题。图像C根本看不到,图像A应该是透明的,有白色。

    cx.putImageData(imageA, 0, 0);
    var resultData = cx.getImageData(0, 0, view.width, view.height);
    
    for (var h=0; h<resultData.data.length; h+=4) {
        resultData.data[h+3] = imageB.data[h];
    }
    
    cx.putImageData(imageC, 0, 0);
    cx.putImageData(resultData, 0, 0);
    

2 个答案:

答案 0 :(得分:17)

Simon是对的:putImageData方法没有注意合成;它只是复制像素值。为了进行合成,我们需要使用绘图操作。

我们需要使用像素数据混淆通道(将红色变为alpha),将更改的像素数据放入图像中,然后然后使用复合操作来获得所需的屏蔽。 / p>

Kinda lame

//copy from one channel to another
var assignChannel = function(imageData, channelTo, channelFrom) {
  if(channelTo < 0 || channelTo > 3 || channelFrom < 0 || channelFrom > 3) {
    throw new Error("bad channel number");
  }
  if(channelTo == channelFrom)
    return;
  var px = imageData.data;
  for(var i = 0; i < px.length; i += 4) {
    px[i + channelTo] = px[i + channelFrom];
  }
};
/**============================================================================ 
  * this function uses 3 or 4 canvases for clarity / pedagogical reasons:
  * redCanvas has our mask image;
  * maskCanvas will be used to store the alpha channel conversion of redCanvas' image;
  * imageCanvas contains the image to be masked;
  * ctx is the context of the canvas to which the masked image will be drawn.
============================================================================**/
var drawOnTopOfRed = function(redCanvas, maskCanvas, imageCanvas, ctx) {
  var redImageData = redCanvas.getContext("2d").getImageData(0, 0, w, h);

  //assign the alpha channel
  assignChannel(redImageData, 3, 0);

  //write the mask image
  maskCanvas.getContext("2d").putImageData(redImageData, 0, 0);

  ctx.save();

  //draw the mask
  ctx.globalCompositeOperation = "copy";
  ctx.drawImage(maskCanvas, 0, 0);

  //draw the image to be masked, but only where both it
  //and the mask are opaque; see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing for details.
  ctx.globalCompositeOperation = "source-in";
  ctx.drawImage(imageCanvas, 0, 0);
  ctx.restore();
};

jsfiddle example

带有示例的涂鸦:

Kinda lame about the same

答案 1 :(得分:2)

因为在步骤4中您使用putImageData来完全替换像素。您想在图像C的顶部绘制图像A,因此您无法执行此操作。相反,您需要使用drawImage()

所以:

cx.putImageData(imageC, 0, 0); // step 3
// create a new canvas and new context,
// call that new context ctx2 and canvas can2:
var can2 = document.createElement('canvas');
// set can2's width and height, get the context etc...
ctx2.putImageData(resultData, 0, 0);
cx.drawImage(can2, 0, 0); // step 4 using drawImage instead of putting image data