【问题标题】:Rotate a line in 3rd dimension on HTML5 canvas在 HTML5 画布上旋转第三维线
【发布时间】:2021-09-09 05:32:00
【问题描述】:

我可以轻松地围绕 z 轴、y 轴或 x 轴绘制/旋转给定长度的线。

const ctx = document.getElementById("drawing").getContext("2d");
ctx.scale(1, -1); ctx.translate(0, -ctx.canvas.height); // flip canvas

const length = 50;
let t = 0;

//x = r sin(q) cos(f)
//y = r sin(q) sin(f)
//z = r cos(q)

function rotate_around_zaxis() {
  const x1=50; const y1=50;
  const line_angle = 20 * Math.PI/180;
  const angle = 0;

  ctx.beginPath(); 
  ctx.moveTo(x1, y1); 
  ctx.lineTo(x1 + length * Math.sin(line_angle) * Math.cos(angle + t), 
             y1 + length * Math.sin(line_angle) * Math.sin(angle + t)); 
  ctx.stroke();
}

function rotate_around_yaxis() {
  const x1=150; const y1=50;
  const line_angle = 20 * Math.PI/180;
  const angle = 0;

  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x1 + length * Math.sin(line_angle) * Math.cos(angle + t), 
             y1 + length /*Math.sin(angle + t)*/ * Math.cos(line_angle) ); 
  ctx.stroke();
}

function rotate_around_xaxis() {
  const x1=250; const y1=50;
  const line_angle = 20 * Math.PI/180;
  const angle = 0;

  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x1 + length /**Math.sin(angle + t)*/ * Math.cos(line_angle), 
             y1 + length * Math.sin(line_angle) * Math.sin(angle + t)); 
  ctx.stroke();
}

function line(x1, y1, x2, y2) {
  ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
}

function animate() {
  ctx.clearRect(0,0,300,100);
  line(0, 50, 100, 50);line(50, 0, 50, 100);rotate_around_zaxis();
  line(105, 50, 200, 50);line(150, 0, 150, 100);rotate_around_yaxis();
  line(205, 50, 300, 50);line(250, 0, 250, 100);rotate_around_xaxis();
  t+=Math.PI/180;
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
<canvas id="drawing" width=300 height=100></canvas>

但是,我只能围绕直线向上/向下 y 轴度数或直线 x 轴执行此操作。我无法弄清楚围绕空间中任意线的旋转。换句话说,我不知道如何将它移动到 3d 空间中 x、y 和 z/ 之间的任何点。

我无法掌握旋转矩阵。很多地方的旋转计算是这样给出的。

x' = x * cos(angle) - y * sin(angle); 
y' = x * sin(angle) + y * cos(angle);

我不明白这个等式在哪里适合我正在尝试做的事情。

我希望能够围绕任何轴以锥形形状旋转线条。我如何做到这一点?

【问题讨论】:

标签: javascript 3d rotation html5-canvas


【解决方案1】:

好吧,理论上,如果第一个示例有效,那么要获得第二个示例,您可以应用第一个示例,然后只需翻译所有内容-60°

let newX2 = Math.cos(-60 / Math.PI/180) * x2
let newY2 = Math.sin(-60 / Math.PI/180) * y2

x1y1 相同

【讨论】:

  • 你能详细说明一下吗?
猜你喜欢
  • 1970-01-01
  • 2015-05-25
  • 2011-03-11
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 2014-09-23
相关资源
最近更新 更多