代码使用了WordCloud库来生成云词,需要先在小程序中引入该库。同时,需要将漂流瓶图片放在/images/bottle.png
路径下。在漂流瓶页面点击按钮后,跳转到云词页面,并将关键字作为参数传递过去。在云词页面中,根据传递过来的关键字生成云词,并将生成的云词图片保存在wordcloudUrl
变量中,用于在页面中显示。
<!-- 云词页面 -->
<view class="container">
<view class="bottle">
<image src="/images/bottle.png" class="bottle-img"></image>
<view class="bottle-text">点击输入关键字生成云词</view>
</view>
<button class="btn" bindtap="onTapBottle">开始生成</button>
</view>
<!-- 云词页面 -->
<view class="container">
<view class="wordcloud">
<image src="{{wordcloudUrl}}" class="wordcloud-img"></image>
</view>
</view>
复制// 漂流瓶页面逻辑
Page({
onTapBottle: function() {
wx.navigateTo({
url: '/pages/wordcloud/wordcloud',
})
}
})
// 云词页面逻辑
Page({
data: {
wordcloudUrl: ''
},
onLoad: function(options) {
// 获取关键字
var keywords = options.keywords.split(',')
// 生成云词
var wordcloud = new window.WordCloud(document.querySelector('.wordcloud-img'), {
list: keywords,
fontFamily: 'Microsoft YaHei',
fontWeight: 'bold',
color: '#333',
backgroundColor: '#fff',
gridSize: Math.round(16 * document.querySelector('.wordcloud-img').width / 1024),
weightFactor: function (size) {
return Math.pow(size, 2.3) * document.querySelector('.wordcloud-img').width / 1024
}
})
// 保存云词图片
this.setData({
wordcloudUrl: wordcloud.toDataURL()
})
}
})
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.bottle {
position: relative;
width: 200px;
height: 200px;
margin-bottom: 50px;
}
.bottle-img {
width: 100%;
height: 100%;
}
.bottle-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 16px;
color: #fff;
text-align: center;
}
.btn {
width: 200px;
height: 40px;
background-color: #007aff;
color: #fff;
border-radius: 20px;
}
.wordcloud {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.wordcloud-img {
max-width: 100%;
max-height: 100%;
}