echart封装词云图

echart封装词云图_第1张图片
ps:忽略箭头

<template>
  <div :id="id" :style="{ width: width, height: height }" />
</template>

<script lang="ts" setup>
import "echarts-wordcloud/dist/echarts-wordcloud";
import "echarts-wordcloud/dist/echarts-wordcloud.min";

interface dataInter{
  name: string,
  value: number,
}
interface Props{
    id?:string,
    cloudData?:dataInter[],
    width?:string,
    height?:string,
    color?:string[],
    textStyleColor?:string
  }
  const props = withDefaults(defineProps<Props>(),{
    id: "wordCloud",
    cloudData: () => {
        return [];
    },
    width:  "100%",
    height: "100%",
    color:  () => {
        return ['#6fdfd1','#f29d5f','#bba1f9','#f37976','#61a0f0','#f4cf6c'];
    },
    textStyleColor: '#000'
  })

  const global: any = inject("global");
    let option: any = {};
    const changeOption = function () {
      option = {}
      option = {
        tooltip: {
          backgroundColor: "",
          // borderColor: 'red',
          textStyle: {
            color: props.textStyleColor,
          },
        },
        grid: {
            top: "0",
            left: "0",
            right: "0",
            bottom: "0",
            containLabel: true,
          },
        series: [
          {
            type: "wordCloud",
            gridSize: 15, // 字之间的间隔大小
            sizeRange: [18, 51], // 最小字体和最大字体 必须写一个范围不能直接写sizeRange: 14,
            rotationRange: [0, 0], // 字体旋转角度的范围,这里水平
            // shape: "smooth", // 形状
            width: "100%",
            height: "100%",
            // drawOutOfBound: false, // 字是否叠加
            textStyle: {
              color: function () {
                if (props.color.length > 1)
                  return props.color[Math.floor(Math.random() * (props.color.length - 1))];
                return props.color[0];
              },
            },
            emphasis: {
              // 字高亮时显示的效果
              textStyle: {
                shadowBlur: 20, // 阴影距离
                shadowColor: "#red", // 阴影颜色
              },
            },
            data: props.cloudData,
          },
        ],
      };
    };
    let mychart:any;
    onMounted(() => {
      if (document.getElementById(props.id)) {
        setTimeout(()=>{
        mychart = global.$echarts.init(document.getElementById(props.id));
        changeOption();
        mychart.setOption(option);
        window.addEventListener("resize", () => {
          mychart.resize();
        });
        },100)
      }
    });

    watch(props, () => {
      try {
        if (mychart != null && mychart != "" && mychart != undefined) {
          mychart.dispose(); //销毁
        }
        mychart = global.$echarts.init(document.getElementById(props.id));
        changeOption();
        mychart.setOption(option);
      } catch (err) {}
    });
</script>
<style >
</style>

你可能感兴趣的:(echarts,前端,javascript)