【问题标题】:Mirroring right half of webcam image镜像网络摄像头图像的右半部分
【发布时间】:2014-05-20 02:47:13
【问题描述】:

我看到您之前曾帮助大卫解决镜像画布问题。 Canvas - flip half the image

我有类似的问题,希望你能帮助我。 我想在我的网络摄像头画布上应用相同的镜像效果,但不是左侧,而是取图像的右半部分,将其翻转并将其应用到左侧。

这是您为 David 发布的代码。它也适用于我的网络摄像头 cancas。现在我尝试更改它,以便它适用于另一方,但不幸的是我无法得到它。

for(var y = 0; y < height; y++) {
for(var x = 0; x < width / 2; x++) { // divide by 2 to only loop through the left half of the image.
    var offset = ((width* y) + x) * 4; // Pixel origin

    // Get pixel
    var r = data[offset];
    var g = data[offset + 1];
    var b = data[offset + 2];
    var a = data[offset + 3];

    // Calculate how far to the right the mirrored pixel is
    var mirrorOffset = (width - (x * 2)) * 4;

    // Get set mirrored pixel's colours 
    data[offset + mirrorOffset] = r;
    data[offset + 1 + mirrorOffset] = g;
    data[offset + 2 + mirrorOffset] = b;
    data[offset + 3 + mirrorOffset] = a;
}

}

【问题讨论】:

  • 您是否尝试过从 width / 2 开始第二个 for 循环并在此之前结束它?至于 (var x = width / 2; x

标签: javascript canvas


【解决方案1】:

即使您所依赖的已接受答案使用 imageData,也绝对没有用处。
Canvas 允许通过 drawImage 及其变换(缩放、旋转、平移)执行许多操作,其中之一就是安全地复制画布本身。
优点是它比通过它的 rgb 组件处理图像更容易和更快。

我会让你阅读下面的代码,希望它的注释足够清晰。
小提琴在这里:

http://jsbin.com/betufeha/2/edit?js,output

一个输出示例 - 我还拿了一座山,一座加拿大山 :-) - :

原文:

输出:

html

<canvas id='cv'></canvas>

javascript

var mountain = new Image() ; 
mountain.onload = drawMe;
mountain.src  = 'http://www.hdwallpapers.in/walls/brooks_mountain_range_alaska-normal.jpg';

function drawMe() {
  var cv=document.getElementById('cv');
  // set the width/height same as image.
  cv.width=mountain.width;
  cv.height = mountain.height;
  var ctx=cv.getContext('2d');
  // first copy the whole image.
  ctx.drawImage(mountain, 0, 0);  
  // save to avoid messing up context.
  ctx.save();
  // translate to the middle of the left part of the canvas = 1/4th of the image.
  ctx.translate(cv.width/4, 0);
  // flip the x coordinates to have a mirror effect
  ctx.scale(-1,1);
  // copy the right part on the left part.
  ctx.drawImage(cv, 
  /*source */  cv.width/2,0,cv.width/2, cv.height,
  /*destination*/  -cv.width/4, 0, cv.width/2, cv.height);
  // restore context
  ctx.restore();  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多