【问题标题】:Calculate 2D rotation javascript HTML canvas计算 2D 旋转 javascript HTML 画布
【发布时间】:2021-06-26 11:26:08
【问题描述】:

实现了一个画布,在那里绘制一个正方形并获取计算坐标,
可以在下图中看到图纸:

我正在计算并获取上点 X 和 Y 坐标,
对于我需要的右下坐标,我添加了高度和宽度,如下所示:

 { upLeft: { x: position.x, y: position.y }, downRight: { x: position.x + position.width, y: position.y + position.height } },

现在我想在顺时针或逆时针旋转画布时获得相同的尺寸。 所以我有角度,我尝试通过以下函数计算:

 function getRotatedCoordinates(cx, cy, x, y, angle) {
    let radians = (Math.PI / 180) * angle,
        cos = Math.cos(radians),
        sin = Math.sin(radians),
        nx = (cos * (x - cx)) - (sin * (y - cy)) + cx,
        ny = (cos * (y - cy)) + (sin * (x - cx)) + cy;
    return [nx, ny];
  }

我正在通过以下参数调用该函数并使用它。

let newCoords = getRotatedCoordinates(0, 0, position.x, position.y, angle);
position.x = newCoords[0];
position.y = newCoords[1];

首先,我不确定 cx 和 cy 点是否正确,我总是为它们输入 0。 其次,我没有得到想要的结果,它们正在发生变化,但我很确定 x 和 y 有问题,所以我猜这个函数是错误的。 谢谢。

【问题讨论】:

  • 当然我正在使用结果,谢谢我会改变它
  • @ChrisG 谢谢,看看我是如何使用它的,我确实根据我已经从函数中获得的内容更改了 position.x 和 position.y,所以那里仍然存在问题。跨度>
  • @ChrisG 确实,但仅在我的实际代码中没有:)。
  • “我不确定 cx 和 cy 点是否正确,我总是为它们输入 0。” - 那你期望它们有什么效果有你的公式吗?如果您甚至不确定输入参数的哪些值实际上是有意义的,那么您从哪里获得该函数 from ;我假设你实际上并没有自己写?
  • @CBroe 这个函数我没写,也没找到其他计算矩阵的函数。我猜 cx 和 cy 是坐标的初始点,这就是为什么我选择 0,0

标签: javascript html angular canvas coordinates


【解决方案1】:

我会这样做:

function getRectangeCoordinates(x, y, width, height, angle) {
  let points = [ [x, y] ]
  let radians = (Math.PI / 180) * angle;
  for (let i = 0; i < 3; i++) {
    x += Math.cos(radians) * ((i == 1) ? height : width);
    y += Math.sin(radians) * ((i == 1) ? height : width);
    points.push([x, y])
    radians += Math.PI / 2
  }
  return points
}

let canvas = document.createElement("canvas");
canvas.width = canvas.height = 140
let ctx = canvas.getContext('2d');
document.body.appendChild(canvas);

function draw(coords, radius) {
  for (let i = 0; i < 4; i++) {
    ctx.beginPath();
    ctx.arc(coords[i][0], coords[i][1], radius, 0, 8);
    ctx.moveTo(coords[i][0], coords[i][1]);
    let next = (i + 1) % 4
    ctx.lineTo(coords[next][0], coords[next][1]);
    ctx.stroke();
  }
}

let coords = getRectangeCoordinates(20, 10, 120, 40, 15)
console.log(JSON.stringify(coords))
draw(coords, 3)

ctx.strokeStyle = "red";
coords = getRectangeCoordinates(60, 40, 40, 50, 65)
draw(coords, 5)

ctx.strokeStyle = "blue";
coords = getRectangeCoordinates(120, 3, 20, 20, 45)
draw(coords, 2)

getRectangeCoordinates中,我返回一个矩形的所有角,函数的参数是左上角(x, y)矩形的高度和宽度,最后是角度。

我正在画几个不同形状和角度的矩形来展示它的样子


函数中的计算是简单的三角函数,这是一个直观的表示,可以帮助您在下次需要时记住它:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2018-10-31
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    相关资源
    最近更新 更多