我希望能够从中心旋转四边形。为此,我按照以下步骤操作:
- 翻译为 (0, 0)
- 旋转
- 返回目的地
我被困在第三点了。当我旋转矩阵时,我想将其相对于屏幕向右移动一个点,但它却相对于旋转向右移动一个点。
这是我的代码:
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]);
如何解决这个问题?
最佳答案
您只需将转换顺序更改为:
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>
关于javascript - 旋转后平移缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46326650/