使用2D渲染上下文的HTML5 Canvas转换问题

8 javascript html5 2d canvas transformation

我正在尝试使用2D渲染上下文在HTML5 Canvas中制作一种相机.正如您在下面的图片中看到的,这是我想要实现的目标:

  1. 假设黑色的是相机的眼睛,我希望它能够移动(编辑:)与画布(如图中的绿色箭头)并且能够看起来像AS如果它绕着物体移动,就像红色的那个(我相信这是视差的东西).
  2. 每当我绕着物体移动时,当我旋转相机时,我希望它通过相机的中心旋转(参见蓝色旋转).

每当我移动相机时,我已经完成了红色框可以在相机中心旋转的位置[编辑],这是一个简化的例子:

*Within the requestAnimationFrame (game loop)*

...

ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);

ctx.save();
    // draw camera eye.
    ctx.lineWidth = 3;
    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.moveTo(ctx.canvas.width / 2 - 50, ctx.canvas.height / 2);
    ctx.lineTo(ctx.canvas.width / 2 + 50, ctx.canvas.height / 2);
    ctx.moveTo(ctx.canvas.width / 2, ctx.canvas.height / 2 - 50);
    ctx.lineTo(ctx.canvas.width / 2, ctx.canvas.height / 2 + 50);
    ctx.stroke();

    // Rotate by camera's center.
    ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);
    ctx.rotate(worldRotate);
    ctx.translate(worldPos.x, worldPos.y);

    //
    // ADD WORLD ENTITIES BELOW to be viewed by the camera.
    //

    ctx.fillStyle = "red";
    ctx.fillRect(-5, -5, 10, 10);
ctx.restore();

...
Run Code Online (Sandbox Code Playgroud)

(编辑:将变换对象更改为ctx以进一步简化代码.)

变量worldRotate和worldPos可通过输入进行测试.

编辑:这是真实的实例,其中包含的问题是为了让我更清楚自己想要实现的目标.

尝试向右或向左移动它,看看会发生什么.并尝试向右旋转相机,使红色框与x轴对齐,然后移动相机,看看它是如何完美地像我想要的相机一样工作.

(注意:推荐的浏览器测试它是IE10,最新的Chrome,最新的firefox,最新的歌剧和5+桌面游猎).

问题是,当我移动相机时(通过改变worldPos,使红色框离开相机),进行旋转(使用worldRotate),然后再次移动相机,红色物体总是朝着紫色箭头移动而不是橙色箭头.无论相机的中心是否旋转,我都希望红色框朝橙色箭头移动.

编辑:据我所知,很明显旋转导致翻译陷入困境,因为旋转会改变红框的坐标系,但我仍然不知道如何处理它,至少让它无论红色框的当前旋转坐标系如何,平移都像橙色箭头一样.

对此有何解决方案?谢谢.

样本图片

Jar*_*rod 0

顺序应该是这样的:

Ctx.save()
Ctx.translate(x, y) //to the center (Or top left of object to rotate)
Ctx.rotates(radian)
Ctx.translate(-x, -y) //important to move the context back!
Ctx.draw(...)
Ctx.restore()
Run Code Online (Sandbox Code Playgroud)