通过 GLSL/WebGL 旋转图像

Rotate an image via GLSL/WebGL

我正在尝试使用 GLSL 旋转图像(通过 glfx.js)。

我已经检查了之前的答案,例如this and ,但结果仍然是一个歪曲的图片(第一个答案),或者答案对于我的初学者水平(第二个)来说有点太简洁了。

我使用的片段着色器是这样的:

uniform sampler2D texture;
uniform vec2 texSize;
varying vec2 texCoord;
uniform float degrees;
const float PI = 3.1415926535897932384626433832795;

float deg2rad(float deg){ return deg * PI / 180.0; }
void main() {
  vec2 coord = texCoord.xy;

  float sin_factor = sin(deg2rad(degrees));
  float cos_factor = cos(deg2rad(degrees));

  coord = coord * mat2(cos_factor, sin_factor, -sin_factor, cos_factor);
  coord = vec2(mod(coord.x, 1.0), mod(coord.y, 1.0));

  vec4 color = texture2D(texture, coord);
  float grey = 0.299 * color.r + 0.587 * color.g + 0.114 * color.b;
  gl_FragColor = vec4(color);

然而,旋转 30 度后生成的图像(我的天花板的网络摄像头照片)是倾斜的,当旋转 180 度时,它会绕 X 轴翻转,但不会绕 Y 轴翻转(即:它是镜像的)。

我需要修复什么才能使图像不倾斜或翻转?

这会将旋转更改为围绕图像中心。它应该可以解决镜像问题,并希望也能解决倾斜问题:

uniform sampler2D texture;
uniform vec2 texSize;
varying vec2 texCoord;
uniform float degrees;
const float PI = 3.1415926535897932384626433832795;
const vec2 HALF = vec2(0.5);

float deg2rad(float deg){ return deg * PI / 180.0; }
void main() {
  vec2 coord = texCoord.xy;

  float sin_factor = sin(deg2rad(degrees));
  float cos_factor = cos(deg2rad(degrees));

  // move rotation origin from upper left to centre of image
  coord -= HALF.xy;
  // rotate image around image centre
  coord *= mat2(cos_factor, sin_factor, -sin_factor, cos_factor);
  // compensate for skew
  coord *= vec2(texSize.y / texSize.x, texSize.x / texSize.y);
  // move origin back to upper left to read from texture
  coord += HALF.xy;

  vec4 color = texture2D(texture, coord);
  float grey = 0.299 * color.r + 0.587 * color.g + 0.114 * color.b;
  gl_FragColor = vec4(color);