gpt4 book ai didi

javascript - 范围内的裁剪线

转载 作者:行者123 更新时间:2023-11-29 22:54:50 25 4
gpt4 key购买 nike

我有一张图表和一条回归线(蓝色的)。现在,线的末端可以从尺寸为 (x0, x1, y0, y1) 的黑色矩形中退出。

我希望蓝线只显示在黑色矩形内。我该怎么办?

我知道坐标:x0, x1, y0, y1, AB。我想知道 CD 的坐标。我需要帮助..

A figure of a rectangle with a line crossing it diagonally

最佳答案

这是 Liang–Barsky 的 javascript 实现。它还使用您的变量名称运行示例计算:

var x0 = 0;
var y0 = 0;
var x1 = 640;
var y1 = 480;
var xa = 20;
var ya = -40;
var xb = 680;
var yb = 460;

// JS port of https://github.com/w8r/liang-barsky/blob/master/src/liang-barsky.ts

const EPSILON = 1e-6;
const INSIDE = 1;
const OUTSIDE = 0;

/**
* @param {Number} num
* @param {Number} denom
* @param {Number[]} c result [x,y]-array
*/
function clipT(num, denom, c) {
const [tE, tL] = c;
if (Math.abs(denom) < EPSILON) return num < 0;
const t = num / denom;

if (denom > 0) {
if (t > tL) return 0;
if (t > tE) c[0] = t;
} else {
if (t < tE) return 0;
if (t < tL) c[1] = t;
}
return 1;
}

/**
* @param {Number[]} a [x,y]-array
* @param {Number[]} b [x,y]-array
* @param {Number[]} box [xmin, ymin, xmax, ymax]-array
* @param {Number[]} da result [x,y]-array
* @param {Number[]} db result [x,y]-array
* @return {Number} Returns OUTSIDE or INSIDE
*/
function clip(a, b, box, da = null, db = null) {
const [x1, y1] = a;
const [x2, y2] = b;
const dx = x2 - x1;
const dy = y2 - y1;

if (da === undefined || db === undefined) {
da = a;
db = b;
} else {
da[0] = a[0];
da[1] = a[1];
db[0] = b[0];
db[1] = b[1];
}

if (Math.abs(dx) < EPSILON && Math.abs(dy) < EPSILON && x1 >= box[0] && x1 <= box[2] && y1 >= box[1] && y1 <= box[3]) {
return INSIDE;
}

const c = [0, 1]; // Point
if (clipT(box[0] - x1, dx, c) && clipT(x1 - box[2], -dx, c) && clipT(box[1] - y1, dy, c) && clipT(y1 - box[3], -dy, c)) {
const [tE, tL] = c;
if (tL < 1) {
db[0] = x1 + tL * dx;
db[1] = y1 + tL * dy;
}
if (tE > 0) {
da[0] += tE * dx;
da[1] += tE * dy;
}
return INSIDE;
}
return OUTSIDE;
}

var da = [null, null];
var db = [null, null];
var res = clip([xa, ya], [xb, yb], [x0, y0, x1, y1], da, db);

var [xc, yc] = da;
var [xd, yd] = db;
console.log(res, xc, yc, xd, yd);

关于javascript - 范围内的裁剪线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56792519/

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