我在畫布上有隨機矩形存盤在一個陣列中,如下所示:
var rectangles = [
{x: 10, y: 10},
{x: 40, y: 50},
{x: 1, y: 70},
{x: 80, y: 5},
{x: 30, y: 60}
];
我現在想根據它們與原點 (0, 0) 的接近程度來標記這些矩形。
我的第一個想法是以不同的模式遍歷 x 和 y 軸,一個例子是:
// 100 is the width and height of the canvas
for(var x = 0; x < 100; x ){
for(var y = 0; y < 100; y ){
// "intersects" loops through the array and returns the matching index or -1 if no match
if(intersects(rectangles, x, y) > -1){
console.log('Rectangle' (intersects(rectangles, x, y) 1));
}
}
}
我遇到的問題是,無論回圈模式如何,結果都不如預期。

我的第二個想法是將矩形繪制到原點(見最后一張影像)并按矩形的大小對其進行排序。但是,這(以及為此計算線距)也沒有產生預期的結果。這可以通過綠色矩形看到,它非常接近 X0,但應該是最后一個。
例如,這應該回傳相同的結果:

有誰知道我如何才能獲得正確的標簽結果?謝謝!
uj5u.com熱心網友回復:
以下是如何將坐標距離與原點進行比較并對它們進行排序(最近到最遠)。
var rectangles = [
{x: 10, y: 10},
{x: 40, y: 50},
{x: 1, y: 70},
{x: 80, y: 5},
{x: 30, y: 60}
];
const sumOfSquares = (x, y) => {
return Math.pow(x, 2) Math.pow(y, 2);
};
rectangles.sort((a, b) => {
const sumA = sumOfSquares(a.x, a.y);
const sumB = sumOfSquares(b.x, b.y);
return sumA - sumB;
});
console.log(rectangles);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369749.html
標籤:javascript 数学 几何学
