vue简单实现词云图组件

3,238 阅读3分钟

「这是我参与2022首次更文挑战的第20天,活动详情查看:2022首次更文挑战」。

说在前面

JavaScript也有许多可以用来生成词云图的库,但我自己其实都没有使用过,之前使用python的时候倒是用过python的wordcloud库,wordcloud库配合jieba库就可以很好的满足词频统计的需求,但在JavaScript这边我还没有了解很多词频统计这块的相关知识,在网上搜索了一番好像都没有搜索到有有关词频统计的相关库,而在词云生成这一方面的相关库倒是发现有不少,如:js2wordcloudwordcloud2 等等……这些库都很好地实现了词云图片的展示,现在我也尝试着简单封装一个自己使用的简洁版词云图

思路

实现效果

词云图需要实现的效果大致可以总结如下:

  • 1、根据词频设置不同的字体大小
  • 2、给单词渲染不同的随机颜色
  • 3、随机排布单词的位置

image.png

关键代码

1、根据词频设置不同的字体大小

maxSize与minSize设置最大字体和最小字体的比例,并不是实际的字体大小,字体大小的计算方式如下:

  • 1、计算最大字体和最小字体的中位数最为基准(该基准的字体大小即为this.baseSize,其余均在此基准上下浮动)
const baseSize = (this.maxSize + this.minSize) / 2;
  • 2、通过词频比例计算出字体的大小的浮动值
const addSize =
        ((this.maxSize - this.minSize) * (freq - this.minFreq)) /
        (this.maxFreq - this.minFreq);
  • 3、计算出具体的字体大小 (字体最小值 + 浮动值) / 基准值 = 实际字体比例 实际字体比例 * 实际设置基准值 = 实际字体大小
((this.minSize + addSize) / baseSize) * this.baseSize + "rem";
  • 4、完整代码如下
//通过词频计算字体大小
getSize(freq) {
    const baseSize = (this.maxSize + this.minSize) / 2;
    const addSize =
        ((this.maxSize - this.minSize) * (freq - this.minFreq)) /
        (this.maxFreq - this.minFreq);
    return (
        ((this.minSize + addSize) / baseSize) * this.baseSize + "rem"
    );
},
2、给单词渲染不同的随机颜色

颜色的rgb值为3个0~255的数字组成,我们只要随机生成3个0~255范围的数字组合即可,具体代码如下:

//随机获取颜色
getRandomColor() {
    let res = "rgb(";
    res += this.getRandomNum(0, 255) + ",";
    res += this.getRandomNum(0, 255) + ",";
    res += this.getRandomNum(0, 255) + ")";
    return res;
},
//获取随机数
getRandomNum(minN, maxN) {
    return Math.floor(Math.random() * (maxN - minN + 1) + minN);
},
3、随机排布单词的位置

对于单词位置排布这边有两个实现方案,但两个方案各有好处与缺点。

  • 1、绝对布局设置单词位置 image.png

优点:单词位置随机性高 缺点:需要处理单词位置重叠问题(选择了方案二,所以目前还没有去解决这个问题) 实现思路: (1)在范围内随机获取坐标

//随机获取坐标
getRandomPoint() {
    const width = this.width,
        height = this.height,
        pointList = this.pointList,
        showTextList = this.showTextList;
    const x = this.getRandomNum(0, width - 20),
        y = this.getRandomNum(0, height - 20);
    return { x: x, y: y };
},

(2)组合对应样式

//组合样式
getStyle(item, index) {
    const height = parseFloat(item.size) * 16;
    const width = parseFloat(item.size) * 20 * item.text.length;
    let res = "";
    res += "font-size:" + item.size + ";";
    res += "position: absolute;";
    res +=
        "top:" +
        Math.max(0, Math.min(item.point.y, this.width - width)) +
        "px;";
    res +=
        "left:" +
        Math.max(0, Math.min(item.point.x, this.height - height)) +
        "px;";
    res += "color:" + item.color + ";";
    return res;
},
  • 2、浮动布局设置单词位置

image.png

优点:单词位置不会重叠 缺点:单词位置随机性低 实现思路: (1)在范围内随机获取坐标

//随机获取坐标
getRandomPoint() {
    const width = this.width,
        height = this.height,
        pointList = this.pointList,
        showTextList = this.showTextList;
    const x = this.getRandomNum(0, width - 20),
        y = this.getRandomNum(0, height - 20);
    return { x: x, y: y };
},

(2)组合对应样式

//组合样式
getStyle(item, index) {
    const height = parseFloat(item.size) * 16;
    const width = parseFloat(item.size) * 20 * item.text.length;
    let res = "";
    res += "float: left;";
    res += "font-size:" + item.size + ";";
    res += "color:" + item.color + ";";
    return res;
},

完整代码

完整代码实现如下:

<template>
    <div>
        <div
            class="j-word-cloud"
            :style="'min-height:' + height + 'px;width:' + width + 'px;'"
        >
            <span
                v-for="(item, index) in showTextList"
                :key="index"
                :id="'word-' + index"
                :style="getStyle(item, index)"
            >
                {{ item.text }}
            </span>
        </div>
        <div @click="init()">刷新</div>
    </div>
</template>

<script>
export default {
    name: "JWordCloud",
    props: {
        textList: {
            type: Array,
            default: () => {
                return [
                    { text: "单词", freq: 10 },
                    { text: "单词1", freq: 5 },
                    { text: "单词2", freq: 7 },
                    { text: "单词3", freq: 2 },
                    { text: "单词5", freq: 3 },
                    { text: "单词6", freq: 4 },
                    { text: "单词7", freq: 5 },
                    { text: "单词8", freq: 6 },
                    { text: "单词9", freq: 6 },
                    { text: "单词10", freq: 8 },
                    { text: "单词11", freq: 4 },
                    { text: "单词12", freq: 2 },
                    { text: "单词13", freq: 4 },
                    { text: "单词14", freq: 3 },
                    { text: "单词15", freq: 1 },
                    { text: "单词16", freq: 5 }
                ];
            }
        },
        width: {
            type: Number,
            default: 300
        },
        colorList: {
            type: Array,
            default: () => []
        },
        baseSize: {
            type: Number,
            default: 2
        },
        maxSize: {
            type: Number,
            default: 5
        },
        minSize: {
            type: Number,
            default: 1
        },
        transformDeg: {
            type: Array,
            default: () => {
                return [-45, 45];
            }
        }
    },
    data() {
        return {
            maxFreq: 0,
            minFreq: 0,
            showTextList: [],
            pointList: [],
            height: 200
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            this.initData();
            this.comShowtexList();
            this.getFourPoints();
        },
        //组合样式
        getStyle(item, index) {
            const height = parseFloat(item.size) * 16;
            const width = parseFloat(item.size) * 20 * item.text.length;
            let res = "";
            res += "font-size:" + item.size + ";";
            // res += "position: absolute;";
            res += "float: left;";
            // res +=
            //     "top:" +
            //     Math.max(0, Math.min(item.point.y, this.width - width)) +
            //     "px;";
            // res +=
            //     "left:" +
            //     Math.max(0, Math.min(item.point.x, this.height - height)) +
            //     "px;";
            res += "color:" + item.color + ";";
            // res += "transform:rotate(" + item.deg + "deg);";
            return res;
        },
        //计算旋转后的坐标
        getTransformPoint(x, y, deg) {
            deg = parseFloat(deg);
            let rx = (Math.cos(deg * Math.PI) / 180) * x,
                ry = (Math.sin(deg * Math.PI) / 180) * x;
            return { tx: x + rx, ty: y + ry };
        },
        //随机获取坐标
        getRandomPoint() {
            const width = this.width,
                height = this.height,
                pointList = this.pointList,
                showTextList = this.showTextList;
            const x = this.getRandomNum(0, width - 20),
                y = this.getRandomNum(0, height - 20);
            return { x: x, y: y };
        },
        //随机获取颜色
        getRandomColor() {
            let res = "rgb(";
            res += this.getRandomNum(0, 255) + ",";
            res += this.getRandomNum(0, 255) + ",";
            res += this.getRandomNum(0, 255) + ")";
            return res;
        },
        //随机获取角度
        getRandomdeg() {
            let res = "";
            res += this.getRandomNum(
                this.transformDeg[0],
                this.transformDeg[1]
            );
            return res;
        },
        //获取随机数
        getRandomNum(minN, maxN) {
            return Math.floor(Math.random() * (maxN - minN + 1) + minN);
        },
        //初始化
        initData() {
            const textList = this.textList;
            let maxF = textList[0].freq,
                minF = textList[0].freq;
            textList.map(item => {
                maxF = Math.max(maxF, item.freq);
                minF = Math.min(minF, item.freq);
            });
            this.maxFreq = maxF;
            this.minFreq = minF;
        },
        //通过词频计算字体大小
        getSize(freq) {
            const baseSize = (this.maxSize + this.minSize) / 2;
            const addSize =
                ((this.maxSize - this.minSize) * (freq - this.minFreq)) /
                (this.maxFreq - this.minFreq);
            return (
                ((this.minSize + addSize) / baseSize) * this.baseSize + "rem"
            );
        },
        //获取四个顶点坐标
        getFourPoints() {
            this.$nextTick(() => {
                let showTextList = this.showTextList;
                let newHeight = 0;
                for (let i = 0; i < showTextList.length; i++) {
                    let id = "word-" + i;
                    let dom = document.getElementById(id);
                    let tl = { x: dom.offsetLeft, y: dom.offsetTop };
                    let tr = {
                        x: dom.offsetLeft + dom.offsetWidth,
                        y: dom.offsetTop
                    };
                    let bl = {
                        x: dom.offsetLeft,
                        y: dom.offsetTop + dom.offsetHeight
                    };
                    let br = {
                        x: dom.offsetLeft + dom.offsetWidth,
                        y: dom.offsetTop
                    };
                    newHeight = Math.max(newHeight, bl.y);
                    showTextList[i].fourPoints = {
                        tl: tl,
                        tr: tr,
                        bl: bl,
                        br: br
                    };
                }
                this.height = newHeight;
            });
        },
        //组装显示列表属性数据
        comShowtexList() {
            let showTextList = [];
            this.textList.map(item => {
                let temp = item;
                temp.size = this.getSize(item.freq);
                const point = this.getRandomPoint();
                const color = this.getRandomColor();
                const deg = this.getRandomdeg();
                this.pointList.push(point);
                temp.point = point;
                temp.color = color;
                temp.deg = deg;
                showTextList.push(temp);
            });
            showTextList = showTextList.sort((a, b) => {
                return 0.5 - Math.random();
            });
            this.showTextList = showTextList;
        }
    }
};
</script>

<style lang="scss" scoped>
.j-word-cloud {
    border: 1px solid black;
    position: relative;
    span {
        transform-origin: 0 0;
        padding: 0.1rem;
        margin: 0 auto;
    }
}
</style>

代码地址

预览(文档):http://120.79.163.94/JYeontuComponents/#/JWordCloudView

gitee源码:gitee.com/zheng_yongt…