画布 - 翻转一半的图像 [英] Canvas - flip half the image

查看:200
本文介绍了画布 - 翻转一半的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在画布上有一些图像数据,现在我需要拿出图像的左半部分,将其翻转并应用到右边,就像一个镜像效果。





至此:





我得到了这么远(我有图像数据准备好):

  ctx.drawImage(this,0,0,960,540 ); 
var imgData = ctx.getImageData(0,0,960,540);
//循环通过数据并应用镜像?

宽度&高度已知。任何想法?

解决方案


  1. 循环浏览图片资料

  2. 如果当前像素在图片的左半部分,请将其复制到右侧位置:





  for(var y = 0; y  for(var x = 0; x  var offset =((width * y)+ x)* 4; //像素原点

//获取像素
var r = data [offset];
var g = data [offset + 1];
var b = data [offset + 2];
var a = data [offset + 3];

//计算镜像像素到右边的距离
var mirrorOffset =(width - (x * 2))* 4;

//获取镜像像素的颜色
data [offset + mirrorOffset] = r;
data [offset + 1 + mirrorOffset] = g;
data [offset + 2 + mirrorOffset] = b;
data [offset + 3 + mirrorOffset] = a;
}
}



我没有测试过,更多或更少)工作,或至少给你一个如何做的想法。


I have some image data in canvas, and now I need to take the left half of the image, flip it and apply it to the right, like a mirror effect.

Example, from this:

To this:

I got this far (I have the image data ready):

ctx.drawImage(this, 0, 0, 960, 540);
var imgData = ctx.getImageData(0,0,960,540);
// loop through the data and apply mirror ??

Width & height is known. Any ideas?

解决方案

  1. Loop through the image data
  2. If the current pixel is in the left half of the image, copy it to a position on the right:

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

I haven't tested this, but it should (More-or less) work, or at least give you an idea of how to do it.

这篇关于画布 - 翻转一半的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆