gpt4 book ai didi

javascript - 如何将此 SVG 三 Angular 形转换为 "wandering"路径表示?

转载 作者:行者123 更新时间:2023-11-30 12:43:54 24 4
gpt4 key购买 nike

请原谅我对几何/数学术语不熟悉。图片将更好地描述我想要完成的事情:

Triangle Example

我想取一个三 Angular 形(例如左边的那个)并从中生成一条路径(例如右边的那个)。每个三 Angular 形将伴随一个亮度值,可用于确定阴影线的频率。

路径上的前两个点应该代表三 Angular 形的一侧,但最后一个点不一定需要落在三 Angular 形的第 3 个点上(尽可能靠近)。

我正尝试在 javascript 中完成此操作,但特定于框架或库的解决方案并不重要。我希望有人能给我指出一些想法/概念,这些想法/概念将帮助我理解几何形状并设计算法。

谢谢

最佳答案

一个有趣的练习。这是我使用纯 Javascript 的解决方案。

基本上我们计算两个线性方程(A->C 和 B->C)。然后将它们分成适当数量的步骤。然后沿着这两条线来回画一条折线。

// 'pts' is a 3x2 array ([3][2]) for the three triangle points
// 'step' is the approximate step distance between lines
function makeTriangle(pts, step)
{
var ax = pts[0][0];
var ay = pts[0][1];
var bx = pts[1][0];
var by = pts[1][1];
var cx = pts[2][0];
var cy = pts[2][1];

// Get AC line length
var a_dx = cx - ax,
a_dy = cy - ay;
var ac_len = Math.sqrt(a_dx * a_dx + a_dy * a_dy);
// Get BC line length
var b_dx = cx - bx,
b_dy = cy - by;
bc_len = Math.sqrt(b_dx * b_dx + b_dy * b_dy);

// Whichever line is shortest will determine the number of steps
var len = (ac_len < bc_len) ? ac_len : bc_len;

// ac step amounts
a_dx = step * a_dx / len;
a_dy = step * a_dy / len;

// bc step amounts
b_dx = step * b_dx / len;
b_dy = step * b_dy / len;

var poly = [];
// first two points
poly.push(ax);
poly.push(ay);
poly.push(bx);
poly.push(by);
while (len > step) {
// step along the ac and bc lines
ax += a_dx;
ay += a_dy;
bx += b_dx;
by += b_dy;
// add the line going from the bc line to the ac line
poly.push(bx);
poly.push(by);
poly.push(ax);
poly.push(ay);
len -= step;
if (len < step) break;
// step again
ax += a_dx;
ay += a_dy;
bx += b_dx;
by += b_dy;
// add line going back again
poly.push(ax);
poly.push(ay);
poly.push(bx);
poly.push(by);
len -= step;
}
poly.push(cx);
poly.push(cy);

// Now we have all our points, build the SVG element
var svg = document.getElementById("mysvg");

var tri = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
tri.setAttribute("fill", "none");
tri.setAttribute("stroke", "black");
tri.setAttribute("stroke-width", 4);
tri.setAttribute("points", poly.join(","));
svg.appendChild(tri);
}


makeTriangle([[117,0],[255,159],[2,279]], 15);

Demo here

关于javascript - 如何将此 SVG 三 Angular 形转换为 "wandering"路径表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23315997/

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