javascript – Canvas:屏蔽图像并保留其alpha通道?

前端之家收集整理的这篇文章主要介绍了javascript – Canvas:屏蔽图像并保留其alpha通道?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我要做的:

>获取图像A和图像B.图像B是黑色和白色的蒙版图像.
>用图像B的红色通道替换图像A的Alpha通道.
>在画布上绘制图像C.
>在图像C的顶部绘制图像A.

一切似乎都可以直到第4步.图像C根本不可见,图像A应该是透明的,有白色.

cx.putImageData(imageA,0);
var resultData = cx.getImageData(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);
cx.putImageData(resultData,0);

解决方法

Simon是对的:putImageData方法不注意合成;它只是复制像素值.为了获得合成,我们需要使用绘图操作.

我们需要将像素数据的通道(变成红色变成alpha),将变化的像素数据放入一个图像中,然后使用复合操作获得所需的掩码.

//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,w,h);

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

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

  ctx.save();

  //draw the mask
  ctx.globalCompositeOperation = "copy";
  ctx.drawImage(maskCanvas,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);
  ctx.restore();
};

jsfiddle example

以涂鸦为例:

猜你在找的JavaScript相关文章