如何解决在 HTML5 画布上的第 3 维中旋转一条线
我可以轻松地围绕 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,300,100);
line(0,50,100,50);line(50,100);rotate_around_zaxis();
line(105,200,50);line(150,150,100);rotate_around_yaxis();
line(205,50);line(250,250,100);rotate_around_xaxis();
t+=Math.PI/180;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
<canvas id="drawing" width=300 height=100></canvas>
但是,我只能围绕直线向上/向下 y 轴度数或直线 x 轴执行此操作。我无法弄清楚围绕空间中任意一条线的旋转。换句话说,我不知道如何将它移动到 x、y 和 z/ 之间的 3d 空间中的任何点。
我无法掌握旋转矩阵。很多地方的轮换计算是这样给出的。
x' = x * cos(angle) - y * sin(angle);
y' = x * sin(angle) + y * cos(angle);
我不明白这个等式适合我正在做的事情。
我希望能够围绕任何轴以锥形形状旋转线条。我如何实现这一目标?
解决方法
好吧,理论上,如果第一个示例有效,那么要获得第二个示例,您可以应用第一个示例,然后只需翻译所有内容-60°
let newX2 = Math.cos(-60 / Math.PI/180) * x2
let newY2 = Math.sin(-60 / Math.PI/180) * y2
x1
和 y1
相同
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。