旋转后平移缓冲区

时间:2017-09-20 15:53:45

标签: javascript matrix webgl image-rotation

我希望能够从中心旋转四边形。为此,我遵循以下步骤:

  1. 翻译成(0,0)
  2. 旋转
  3. 返回目的地点
  4. 我被困在第三点。当我旋转矩阵时,我想将它相对于屏幕向右移动一个点,但它相对于旋转向右移动一个点。

    enter image description here

    这是我的代码:

    var moveBackX = ((-usedSprite.originX)/usedViewWidth);
    var moveBackY = (((usedSprite.originY)))/usedViewHeight;
    //The translation is already at (0, 0, 0)
    mat4.rotateZ(mvMatrix, mvMatrix, rotation);
    mat4.translate(mvMatrix, mvMatrix, [(moveBackX)/scaleX, moveBackY/scaleY, 0.0]);
    
    mat4.translate(mvMatrix, mvMatrix, [((xPos)/scaleX), (-(yPos)/scaleY), 0.0]);
    

    我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

您只需将转换顺序更改为:

mat4.rotateZ(mvMatrix, mvMatrix, rotation);
mat4.translate(mvMatrix, mvMatrix, [(moveBackX)/scaleX, moveBackY/scaleY, 0.0]);

mat4.translate(mvMatrix, mvMatrix, [((xPos)/scaleX), (-(yPos)/scaleY), 0.0]);

以下是使用Context2D进行的一点演示:



const ctx = maincanvas.getContext('2d');

maincanvas.width = 320;
maincanvas.height = 240;

function drawRect(color) {
  ctx.strokeStyle = color;
  ctx.beginPath();
  ctx.rect(0, 0, 50, 50);
  ctx.stroke();
}

ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.translate(100, 0);
drawRect('#ff8888');
ctx.rotate(Math.PI/12);
drawRect('#ff0000');

ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.rotate(Math.PI/12);
drawRect('#88ff88');
ctx.translate(100, 0);
drawRect('#00ff00');

canvas {
  width: 320px;
  height: 240px;
  border: 1px solid black;
}

<canvas id='maincanvas'></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您必须在我们称之为“#34;世界空间&#34;而不是&#34;本地空间&#34;。看来你的mat4.translate()函数在本地空间中执行转换。

更清楚的是,翻译函数的作用是将平移向量乘以变换矩阵的旋转/缩放部分,从而沿着对象的局部轴(即局部空间)生成此平移)。为了防止这种情况,您只需将转换向量添加到转换矩阵的转换部分即可。

让我们假设以下转换4x4矩阵:

Xx Xy Xz 0 // <- X axis
Yx Yy Yz 0 // <- Y axis
Zx Zy Zz 0 // <- Z axis
Tx Ty Tz 1 // <- Translation

其中:

mat4[ 0] = Xx; mat4[ 1] = Xy;  mat4[ 2] = Xz; mat4[ 3] = 0; 
mat4[ 4] = Yx; mat4[ 5] = Yy;  mat4[ 6] = Yz; mat4[ 7] = 0; 
mat4[ 8] = Zx; mat4[ 9] = Zy;  mat4[10] = Zz; mat4[11] = 0; 
mat4[12] = Tx; mat4[13] = Ty;  mat4[14] = Tz; mat4[15] = 1;

旋转/缩放部分(轴)是[0]到[10]中定义的3x3矩阵(不包括[3],[7]和[11])。翻译部分是[12],[13]和[14]。

要在世界空间中为此转换矩阵添加转换,您只需执行以下操作:

mat4[12] += TranslationX;
mat4[13] += TranslationY;
mat4[14] += TranslationZ;
相关问题