支持定義任意多個屬性值,簡單好用!文章底部獲取完整代碼!

如何使用
- 新建一個節點
- 為節點添加
graphics組件 - 添加用戶腳本
radar - 調整對應引數

實作原理
需求可以轉化成如何畫一個有特點的多邊形,
先觀察一下,雷達圖的每個屬性有什么特點,

可以看到每個屬性值,都是在固定虛線上移動,
而且每條線的夾角都是一樣的,這個夾角就是 360度 除以 總共屬性數量,
const radians_per = Math.PI * 2 / this.side_count;
所以我們可以按照屬性次序確定與x軸的夾角,如果我們把第一個屬性值放在y軸,那么初始角度為 90,
// 初始邊放在y軸,多90度
const radians = side_i * radians_per + Math.PI / 2;
虛線的長度可以由總長度和需要的百分比求出,
const side_length = this.side_max_length * percent;
接著根據極坐標到直角坐標系的轉換,就能求出該屬性的坐標,
// 坐標計算 x = r * cos y = r * sin
const posX = side_length * Math.cos(radians);
const posY = side_length * Math.sin(radians);
最后將所有的點連起來,完成雷達圖的繪制,完整的繪制代碼如下,
this.graphics.clear();
// 每個夾角
const radians_per = Math.PI * 2 / this.side_count;
for (let side_i = 0; side_i < this.side_count; side_i++) {
const percent = (this.side_percent[side_i] || 0) / 100;
// 每個邊的長度
const side_length = this.side_max_length * percent;
// 初始邊放在y軸,多90度
const radians = side_i * radians_per + Math.PI / 2;
// 坐標計算 x = r * cos y = r * sin
const posX = side_length * Math.cos(radians);
const posY = side_length * Math.sin(radians);
if (side_i === 0) {
this.graphics.moveTo(posX, posY);
} else {
this.graphics.lineTo(posX, posY);
}
}
this.graphics.close();
this.graphics.stroke();
this.graphics.fill();
以上為白玉無冰使用 Cocos Creator v2.2.2 開發"雷達圖"的技術分享,更多精彩歡迎關注wx公中號【白玉無冰】!如果這篇對你有點幫助,歡迎分享給身邊的朋友,
完整代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/3898.html
標籤:其他
下一篇:版本管理
