【问题标题】:HTML5 Canvas translate, rotate, scaleHTML5 Canvas 翻译、旋转、缩放
【发布时间】:2022-01-10 16:18:58
【问题描述】:

对于一个小游戏,我为 html5 画布编写了一个相机组件。您应该能够缩放(鼠标滚轮)、平移(鼠标左键)和旋转(鼠标右键)。如果您尝试向上移动,我的问题是旋转后方向错误并且图像向下移动。

我在这里准备了一个例子:

https://codepen.io/rogerbuecker/pen/yLzYqXq

我当前的绘制代码:

canvas.width = window.innerWidth
canvas.height = window.innerHeight
    
// Translate to the canvas centre before zooming - so you'll always zoom on what you're looking directly at
ctx.translate( window.innerWidth / 2, window.innerHeight / 2 )
ctx.rotate(cameraRotation*Math.PI / 180)
ctx.scale(cameraZoom, cameraZoom)
ctx.translate( -window.innerWidth / 2 + cameraOffset.x, -window.innerHeight / 2 + cameraOffset.y )

问候罗杰

【问题讨论】:

  • 你所说的方向到底是什么意思?同样出于好奇,在第一次翻译之前调用ctx.save() 并在最后一次翻译之后调用ctx.restore() 是否可以解决问题?
  • 将图像旋转 180 度后,当我想通过拖放向上移动图像时,它会向下移动。 ctx.save 和 restore 在这里没有帮助

标签: javascript html canvas html5-canvas


【解决方案1】:

我找到了解决办法:

https://codepen.io/rogerbuecker/pen/yLzYqXq

错过了我 invertSelf 转换以获得位置的部分

var transform = ctx.getTransform();
const invMat = transform.invertSelf();

【讨论】:

  • 平移有效,但非常有问题。旋转在 Chrome 中失控。
【解决方案2】:

我对画布没有太多经验,但对 css 变换属性有一点经验。

尝试创建一个容器对象,在其中放置您现在拥有的任何东西。然后,当您需要移动图像或与持久方向相关的东西时,只需将您想要的任何东西移动或应用到大容器,然后旋转到其中的小容器。

让我知道它是否适合你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-27
    • 2012-03-22
    • 1970-01-01
    • 2022-01-04
    • 2017-06-05
    • 2019-05-29
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多