屏蔽图像并保留其

屏蔽图像并保留其

本文介绍了画布:屏蔽图像并保留其 Alpha 通道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:

  1. 获取图片 A 和图片 B.图片 B 是黑白蒙版图片.
  2. 将图片 A 的 alpha 通道替换为图片 B 的红色通道.
  3. 在画布上绘制图像 C.
  4. 在图像 C 上绘制图像 A.

在第 4 步之前一切正常.图像 C 根本不可见,图像 A 应该透明的地方是白色.

Everything seems ok until step 4. Image C isn't visible at all and where image A should be transparent there's white color.

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);

推荐答案

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

Simon is right: the putImageData method does not pay any attention to compositing; it merely copies pixel values. In order to get compositing, we need to use drawing operations.

我们需要用像素数据来处理通道(将红色变为 alpha),将更改后的像素数据放入图像中,然后然后使用复合操作来获得所需的遮罩.

We need to mess with the channels (turn red into alpha) with the pixel data, put that changed pixel data into an image, and then use a composite operation to get the desired masking.

//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 示例

带有示例的涂鸦:

这篇关于画布:屏蔽图像并保留其 Alpha 通道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:25