词云开发
效果展示
项目使用
npm install cloudword -S
// 在 main.js 里面引用
import cloudWord from 'cloudWord'
new cloudWord({
el: '#cloudWord', // 云文字容器
words: ['one', 'two', 'three'],
colors: ['red', 'yellow', 'green'],
onClick(elem) {
console.log('点击的文字信息:', elem)
}
})
github 地址 https://github.com/jiayunfei/cloudwords
代码解析
类的初始化
在src下面创建一个index.js文件,里面定义一个cloudWords的类
export default class CloudWords {
constructor(options = {}) {
// 容器
this.$el = this.getElement(options.el)
// 需要展示的文字列表
this.$words = options.words || []
// 需要显示的颜色列表,如果没有就去获取随机颜色
this.$colors = options.colors || getDefaultColors()
// 是否设置触摸停止
this.$touchStop = options.touchStop || true
// 在容器里面展示的最小字号
this.minSize = parseInt(options.minSize || 14)
// 在容器里面展示的最大字号
this.maxSize = parseInt(options.maxSize || 26)
// 点击事件回调
if (typeof options.onClick === 'function') {
this.onClick = options.onClick
}
// 定义将文本信息和文本dom封装的列表
this.elems = []
// 二层容器
this.container = null
// 执行创建dom的操作
this.createWordDoms()
}
}
创建文本dom对象
接下来就是创建dom对象的操作了
createWordDoms () {
this.container = document.createElement('div')
this.container.classList.add('cloud-word-container')
this.$words.forEach(word => {
this.addWord(word, true)
})
this.$el.appendChild(this.container)
// 另包含文本的dom对象动起来
this.setDomsMove()
}
文本dom对象运动初始化
setElemMove (elem) {
const dom = elem.el
// 引用WordMove,另文本dom对象动起来
elem.move = new WordMove(dom, this.$el)
if (this.$touchStop) {
// 引出一个新的类 EventHandler,用来注册事件的
elem.events = new EventHandler(elem, this)
}
}
然后就是执行文本运动逻辑
// wordMove.js
export default class WordMove {
constructor(dom, container) {
this.times = 0
// 每个文本的容器
this.$el = dom
this.$container = container
this.isMoveOver = false
const { randomX, randomY } = getBoundary(dom, container)
this.randomX = randomX
this.randomY = randomY
this.speedX = this.getSpeed()
this.speedY = this.getSpeed()
// 记录文本dom对象的位置
this.model = {
x: 0,
y: 0
}
this.animation = null
this.registeMove()
}
...
}
使用window.requestAnimationFrame方法,让我们的文本一直动起来
registeMove () {
if (this.isMoveOver) {
return
}
this.model.x += this.speedX
this.model.y += this.speedY
this.isInnerContainer()
if (this.times < 100) {
this.animation = window.requestAnimationFrame(this.registeMove.bind(this))
this.times = 0
this.$el.style.transform = `translate(${this.model.x}px, ${this.model.y}px)`
}
}
添加事件响应
我们的文本是动起来了,但是我们还想让动起来之后鼠标覆盖能够停止运动,并且文字字号还能变为最大,而且有些业务需要跳转什么的,就需要注册mouseover,click等响应函数来实现了
export default class EventHandler {
constructor(elem, ctx) {
this.el = elem.el
this.elem = elem
this.ctx = ctx
this.registHandler()
}
registHandler () {
this.el.onmouseover = () => {
this.el.style.cursor = 'pointer'
this.elem.move.stop()
}
this.el.onclick = () => {
this.el.style.cursor = 'default'
this.ctx.onClick && this.ctx.onClick(this.elem)
}
this.el.onmouseleave = () => {
this.elem.move.restart()
}
}
}
总结
这就是以上的内容,觉得有用的话就下载看一看吧