繁体   English   中英

旋转矩形上的Javascript Canvas相对鼠标坐标?

[英]Javascript Canvas Relative Mouse Coordinates on Rotated Rectangle?

我试图将画布中的矩形视为一张纸,当我将鼠标悬停在同一点上时,无论页面的缩放、旋转或平移如何,都会返回相同的相对坐标。

目前,在纵向或倒置纵向旋转时,无论缩放/平移如何,我都能得到准确的结果。 但是,当我切换到横向或倒置横向时,我的结果是关闭的。

试图用我找到的一些三角函数切换到旋转鼠标坐标,但数学不是我的强项,它没有用。

如果有人能指出我正确的方向,我将不胜感激。 我怀疑在旋转横向时我需要交换轴或高度/宽度,但这也没有取得成果。

R 键将“页面”旋转 4、90 度变化。 鼠标相对于页面的坐标,固定在页面的宽度/高度上,会显示在控制台中。

https://jsfiddle.net/2hg6u3wd/2/ (注意,JSFiddle 因未知原因略微偏移坐标)

const orientation = Object.freeze({
  portrait: 0,
  landscape: -90,
  invertedPortrait: 180,
  invertedLandscape: 90
});

function CameraRotate(rotation) {
  // Rotates using the center of target as origin. 
  ctx.translate(target.width / 2, target.height / 2);
  ctx.rotate(-(currentRot * Math.PI / 180)); // Negate currentRot because ctx.rotate() is additive.
  ctx.rotate(rotation * Math.PI / 180);
  ctx.translate(-(target.width / 2), -(target.height / 2));
  currentRot = rotation;
}

function CameraCalcRelTargetCoords(viewX, viewY) {
  return {
    x: clamp((viewX - ctx.getTransform().e) / ctx.getTransform().a, 0, page.width),
    y: clamp((viewY - ctx.getTransform().f) / ctx.getTransform().d, 0, page.height)
  };
}

function clamp(number, min, max) {
  return Math.max(min, Math.min(number, max));
}

canvas.addEventListener(`mousemove`, function(e) {
    console.log(CameraCalcRelTargetCoords(e.x, e.y));
});

当旋转 (-) 180 度时,由于轴被翻转,刻度被存储为倾斜。 因此,您必须除以 m12 和 m21。 这种翻转也意味着 x 和 y 鼠标坐标也需要交换。

这是我的解决方案

function CameraCalcRelTargetCoords(viewX, viewY) {
    // Mouse coordinates are translated to a position within the target's rectangle.
    let relX, relY

    if (currentRot == orientation.landscape || currentRot == orientation.invertedLandscape) {
        // Landscape rotation uses skewing for scale as X/Y axis are flipped.
        relX = clamp((viewY - ctx.getTransform().f) / ctx.getTransform().b, 0, target.width);
        relY = clamp((viewX - ctx.getTransform().e) / ctx.getTransform().c, 0, target.height);
    } else {
        relX = clamp((viewX - ctx.getTransform().e) / ctx.getTransform().a, 0, target.width),
        relY = clamp((viewY - ctx.getTransform().f) / ctx.getTransform().d, 0, target.height)
    }

    return {x: relX, y: relY};
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM