雷达图的一种实现! Cocos Creator !

支持定义任意多个属性值,简单好用!文章底部获取完整代码!git

如何使用github

  1. 新建一个节点
  2. 为节点添加graphics组件
  3. 添加用户脚本radar
  4. 调整对应参数

实现原理ide

需求能够转化成如何画一个有特色的多边形。this

先观察一下,雷达图的每一个属性有什么特色。code

能够看到每一个属性值,都是在固定虚线上移动。blog

并且每条线的夹角都是同样的。这个夹角就是 360度 除以 总共属性数量开发

const radians_per = Math.PI * 2 / this.side_count;

因此咱们能够按照属性次序肯定与x轴的夹角。若是咱们把第一个属性值放在y轴,那么初始角度为 90get

// 初始边放在y轴,多90度
const radians = side_i * radians_per + Math.PI / 2;

虚线的长度能够由总长度和须要的百分比求出。it

const side_length = this.side_max_length * percent;

接着根据极坐标到直角坐标系的转换,就能求出该属性的坐标。ast

// 坐标计算 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公中号【白玉无冰】!若是这篇对你有点帮助,欢迎分享给身边的朋友。

完整代码

相关文章
相关标签/搜索