1.创建一个新的UniApp项目,在pages目录下创建一个新的页面,命名为wordcloud。
2.在wordcloud.vue文件中添加一个canvas元素,用于绘制词云图。如下所示:
<template>
<canvas id="myCanvas"></canvas>
</template>
3.在页面的script中,导入第三方词云库,如wordcloud2.js。可以通过npm安装该库,也可以将其直接下载到项目中,并在script中引用:
import wordcloud2 from '@/utils/wordcloud2.js'
4.在页面的mounted生命周期钩子中,获取canvas元素,设置其宽高和背景颜色:
mounted() {
const canvas = uni.createSelectorQuery().select('#myCanvas')
canvas.fields({ node: true, size: true }).exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
canvas.width = res[0].width
canvas.height = res[0].height
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 调用生成词云的方法
this.generateWordCloud(canvas)
})
},
5.定义一个方法,用于生成词云图。可以从后端获取数据,也可以在前端定义一个数据数组,然后将其传入词云库的options中进行渲染:
methods: {
generateWordCloud(canvas) {
const words = [
{ text: 'hello', size: 12 },
{ text: 'world', size: 20 },
{ text: 'uniapp', size: 16 },
{ text: 'wordcloud', size: 18 },
{ text: 'openai', size: 14 },
]
wordcloud2(canvas, {
list: words,
fontFamily: 'Arial',
fontWeight: 'bold',
color: 'random-dark',
backgroundColor: '#fff',
shape: 'circle',
gridSize: 8,
rotateRatio: 0.5,
})
},
},
6.最后,在manifest.json文件中配置页面的导航栏和标题等信息,然后运行项目即可在词云页面中看到生成的词云图。