gpt4 book ai didi

javascript - 在圆内绘制平行等距线

转载 作者:行者123 更新时间:2023-12-03 01:06:17 24 4
gpt4 key购买 nike

我正在尝试在圆内绘制平行等距线。我已经到了这样的阶段:如果我从圆周上的相对 Angular 连接点,我会得到平行线...但它们不是等距的...

non-equidistant parallel lines

这是一些代码:

var num_lines = 8;
var num_points = num_lines * 2;
var start_angle = 100;
var points = [];
var radius = 200;
ctx.strokeCircle(w/2, h/2, radius, radius); // shorthand for ctx.arc( x, y, 5, 0, Math.PI * 2, true );

for (var i = 0; i < num_points; i++) {
var angle = 360/num_points * i;
ctx.fillStyle = "red";
if (i %2 == 0 ) ctx.fillStyle = "blue";
var x = w/2 + Math.cos(angle) * radius/2;
var y = h/2 + Math.sin(angle) * radius/2;
ctx.circle(x, y, 10, 10); // shorthand for ctx.arc( x, y, 5, 0, Math.PI * 2, true );
points.push({x: x, y: y});
}

for (var i = 0; i < num_lines; i++) {
ctx.line(points[i].x, points[i].y, points[points.length-i-1].x, points[points.length-i-1].y)
}

最佳答案

使用毕达哥拉斯定理

...

  • y:线相对于中心的垂直位置
  • x:其端点距中心的水平距离
  • r:圆的半径

...必须满足y^2 + x^2 = r^2

代码:

var radius = 200;
var num_lines = 8;

// vertical spacing
var delta_y = (2.0 * radius) / (num_lines + 1);

ctx.strokeCircle(w/2, h/2, radius, radius);
for (var i = 0; i < num_lines; i++)
{
// applying pythagoras
var y = delta_y * (i + 1) - radius / 2;
var x = Math.sqrt(radius * radius - y * y);

// calculating endpoints
var left_x = w / 2 - x;
var right_x = w / 2 + x;
var end_y = h / 2 + y;

ctx.fillStyle = (i % 2 == 0) ? "blue" : "red";
ctx.circle(left_x, end_y, 10, 10);
ctx.circle(right_x, end_y, 10, 10);
ctx.line(left_x, end_y, right_x, end_y);
}
<小时/>

编辑:旋转

将矢量顺时针旋转 Angular a:

x' = x * cos(a) + y * sin(a)
y' = y * cos(a) - x * sin(a)

代码:

var radius = 200;
var num_lines = 50;
var angle = 60;

// temporary variables
var delta_y = (2.0 * radius) / (num_lines);
var cos_a = Math.cos(angle * Math.PI / 180.0);
var sin_a = Math.sin(angle * Math.PI / 180.0);

ctx.strokeCircle(w / 2, h / 2, radius * 2, radius * 2);

for (var i = 0; i < num_lines; i++)
{
// applying pythagoras
var y = delta_y * i - radius;
var x = Math.sqrt(radius * radius - y * y);

// rotating the displacement vector
var left_x = y * sin_a + x * cos_a;
var right_x = y * sin_a - x * cos_a;
var left_y = y * cos_a - x * sin_a;
var right_y = y * cos_a + x * sin_a;

ctx.fillStyle = (i % 2 == 0) ? "blue" : "red";
ctx.line(w / 2 + left_x , h / 2 + left_y ,
w / 2 + right_x, h / 2 + right_y);
}

关于javascript - 在圆内绘制平行等距线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52390712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com