亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從給定的坐標(x,y)計算邊界框的寬度和高度

從給定的坐標(x,y)計算邊界框的寬度和高度

梵蒂岡之花 2023-02-24 15:25:36
我有一個坐標列表const coords = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}];我想知道是否有一種方法可以計算僅具有這些坐標的邊界框寬度和高度?
查看完整描述

3 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

使用該map()函數將輸入數組轉換為x或y值的數組。然后,您可以將這些轉換后的數組提供給Math.min()并Math.max()獲得left、right,bottom并top計算bounding box。當你有 時bounding box,寬度和高度的計算是直接的(從最大值中減去最小值)。請參閱下面的代碼片段。


const coords = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}];

const xArr = coords.map(c => c.x);

const yArr = coords.map(c => c.y);


const l = Math.min(...xArr);

const r = Math.max(...xArr);

const b = Math.min(...yArr);

const t = Math.max(...yArr);


const width  = r - l;

const height = t - b;

console.log(width, height);


查看完整回答
反對 回復 2023-02-24
?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

x我想,這將是(寬度)和(高度)的最小值和最大值之間的差異y。

http://img1.sycdn.imooc.com//63f866950001440306530382.jpg

雖然計算這些的明顯方法似乎是使用Math.max()/Math.min()過度提取坐標數組,但它需要多次不必要地循環源數組,而單次傳遞(例如 with Array.prototype.reduce())就足夠了,并且當輸入數組相對大的:


const points = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}],


      {width, height} = points.reduce((acc, {x,y}) => {

            const {min, max} = Math

            if(!acc.mX || x < acc.mX){

              acc.mX = x

            } else if (!acc.MX || x > acc.MX){

              acc.MX = x

            }

            if(!acc.mY || y < acc.mY){

              acc.mY = y

            } else if (!acc.MY || y > acc.MY){

              acc.MY = y

            }

            acc.width = acc.MX - acc.mX

            acc.height = acc.MY - acc.mY

            return acc

          }, {width: 0, height: 0})

          

console.log(`width: ${width}; height: ${height}`)


查看完整回答
反對 回復 2023-02-24
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

看看這個片段。猜猜這是一種開始的方法。


一些解釋

我們正在使用 計算坐標集的 minX、maxX、minY 和 maxY 值Math.operationMinOrMax(...coords.map(c => c.propertyXorY))。

  • 邊界框的 min-x 坐標(=> 左角)是 minX 值。

  • 邊界框的 min-y 坐標 ( => top ) 是 minY 值。


  • 邊界框的 max-x 坐標(=> 右角)是 maxX 值。

  • 邊界框 ( => bottom ) 的 max-y 坐標是 maxY 值。


大?。▽傩?strong>w和hmaxX - minX )可以通過減去和來計算maxY - minY。

const boundingBox = (coords) => {

  const minX = Math.min(...coords.map(c => c.x)), maxX = Math.max(...coords.map(c => c.x));

  const minY = Math.min(...coords.map(c => c.y)), maxY = Math.max(...coords.map(c => c.y));

  return {

    x: minX,

    y: minY,

    w: maxX - minX,

    h: maxY - minY

  }

}

console.log(

  boundingBox( [ {x:10,y:5}, {x:100,y:0}, {x:100,y:100}, {x:12,y:50}, {x:0,y:100}, {x:27,y:22} ])

);


查看完整回答
反對 回復 2023-02-24
  • 3 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號