本文主要对如下技术要点进行分析:javascript
为了让本文更加容易理解,我将以上技术要点结合在一块儿写了一个可视化拖拽组件库 DEMO:css
建议结合源码一块儿阅读,效果更好(这个 DEMO 使用的是 Vue 技术栈)。html
先来看一下页面的总体结构。vue
这一节要讲的编辑器其实就是中间的画布。它的做用是:当从左边组件列表拖拽出一个组件放到画布中时,画布要把这个组件渲染出来。java
这个编辑器的实现思路是:git
componentData
维护编辑器中的数据。push()
方法将新的组件数据添加到 componentData
。v-for
指令遍历 componentData
,将每一个组件逐个渲染到画布(也可使用 JSX 语法结合 render()
方法代替)。编辑器渲染的核心代码以下所示:github
<component
v-for="item in componentData"
:key="item.id"
:is="item.component"
:style="item.style"
:propValue="item.propValue"
/>
复制代码
每一个组件数据大概是这样:vuex
{
component: 'v-text', // 组件名称,须要提早注册到 Vue
label: '文字', // 左侧组件列表中显示的名字
propValue: '文字', // 组件所使用的值
icon: 'el-icon-edit', // 左侧组件列表中显示的名字
animations: [], // 动画列表
events: {}, // 事件列表
style: { // 组件样式
width: 200,
height: 33,
fontSize: 14,
fontWeight: 500,
lineHeight: '',
letterSpacing: 0,
textAlign: '',
color: '',
},
}
复制代码
在遍历 componentData
组件数据时,主要靠 is
属性来识别出真正要渲染的是哪一个组件。api
例如要渲染的组件数据是 { component: 'v-text' }
,则 <component :is="item.component" />
会被转换为 <v-text />
。固然,你这个组件也要提早注册到 Vue 中。数组
若是你想了解更多 is
属性的资料,请查看官方文档。
原则上使用第三方组件也是能够的,但建议你最好封装一下。不论是第三方组件仍是自定义组件,每一个组件所需的属性可能都不同,因此每一个组件数据能够暴露出一个属性 propValue
用于传递值。
例如 a 组件只须要一个属性,你的 propValue
能够这样写:propValue: 'aaa'
。若是须要多个属性,propValue
则能够是一个对象:
propValue: {
a: 1,
b: 'text'
}
复制代码
在这个 DEMO 组件库中我定义了三个组件。
图片组件 Picture
:
<template>
<div style="overflow: hidden">
<img :src="propValue">
</div>
</template>
<script> export default { props: { propValue: { type: String, require: true, }, }, } </script>
复制代码
按钮组件 VButton
:
<template>
<button class="v-button">{{ propValue }}</button>
</template>
<script> export default { props: { propValue: { type: String, default: '', }, }, } </script>
复制代码
文本组件 VText
:
<template>
<textarea v-if="editMode == 'edit'" :value="propValue" class="text textarea" @input="handleInput" ref="v-text" ></textarea>
<div v-else class="text disabled"> <div v-for="(text, index) in propValue.split('\n')" :key="index">{{ text }}</div> </div>
</template>
<script> import { mapState } from 'vuex' export default { props: { propValue: { type: String, }, element: { type: Object, }, }, computed: mapState([ 'editMode', ]), methods: { handleInput(e) { this.$emit('input', this.element, e.target.value) }, }, } </script>
复制代码
一个元素若是要设为可拖拽,必须给它添加一个 draggable
属性。另外,在将组件列表中的组件拖拽到画布中,还有两个事件是起到关键做用的:
dragstart
事件,在拖拽刚开始时触发。它主要用于将拖拽的组件信息传递给画布。drop
事件,在拖拽结束时触发。主要用于接收拖拽的组件信息。先来看一下左侧组件列表的代码:
<div @dragstart="handleDragStart" class="component-list">
<div v-for="(item, index) in componentList" :key="index" class="list" draggable :data-index="index">
<i :class="item.icon"></i>
<span>{{ item.label }}</span>
</div>
</div>
复制代码
handleDragStart(e) {
e.dataTransfer.setData('index', e.target.dataset.index)
}
复制代码
能够看到给列表中的每个组件都设置了 draggable
属性。另外,在触发 dragstart
事件时,使用 dataTransfer.setData()
传输数据。再来看一下接收数据的代码:
<div class="content" @drop="handleDrop" @dragover="handleDragOver" @click="deselectCurComponent">
<Editor />
</div>
复制代码
handleDrop(e) {
e.preventDefault()
e.stopPropagation()
const component = deepCopy(componentList[e.dataTransfer.getData('index')])
this.$store.commit('addComponent', component)
}
复制代码
触发 drop
事件时,使用 dataTransfer.getData()
接收传输过来的索引数据,而后根据索引找到对应的组件数据,再添加到画布,从而渲染组件。
首先须要将画布设为相对定位 position: relative
,而后将每一个组件设为绝对定位 position: absolute
。除了这一点外,还要经过监听三个事件来进行移动:
mousedown
事件,在组件上按下鼠标时,记录组件当前的位置,即 xy 坐标(为了方便讲解,这里使用的坐标轴,实际上 xy 对应的是 css 中的 left
和 top
。mousemove
事件,每次鼠标移动时,都用当前最新的 xy 坐标减去最开始的 xy 坐标,从而计算出移动距离,再改变组件位置。mouseup
事件,鼠标抬起时结束移动。handleMouseDown(e) {
e.stopPropagation()
this.$store.commit('setCurComponent', { component: this.element, zIndex: this.zIndex })
const pos = { ...this.defaultStyle }
const startY = e.clientY
const startX = e.clientX
// 若是直接修改属性,值的类型会变为字符串,因此要转为数值型
const startTop = Number(pos.top)
const startLeft = Number(pos.left)
const move = (moveEvent) => {
const currX = moveEvent.clientX
const currY = moveEvent.clientY
pos.top = currY - startY + startTop
pos.left = currX - startX + startLeft
// 修改当前组件样式
this.$store.commit('setShapeStyle', pos)
}
const up = () => {
document.removeEventListener('mousemove', move)
document.removeEventListener('mouseup', up)
}
document.addEventListener('mousemove', move)
document.addEventListener('mouseup', up)
}
复制代码
因为拖拽组件到画布中是有前后顺序的,因此能够按照数据顺序来分配图层层级。
例如画布新增了五个组件 abcde,那它们在画布数据中的顺序为 [a, b, c, d, e]
,图层层级和索引一一对应,即它们的 z-index
属性值是 01234(后来居上)。用代码表示以下:
<div v-for="(item, index) in componentData" :zIndex="index"></div>
复制代码
若是不了解 z-index
属性的,请看一下 MDN 文档。
理解了这一点以后,改变图层层级就很容易作到了。改变图层层级,便是改变组件数据在 componentData
数组中的顺序。例若有 [a, b, c]
三个组件,它们的图层层级从低到高顺序为 abc(索引越大,层级越高)。
若是要将 b 组件上移,只需将它和 c 调换顺序便可:
const temp = componentData[1]
componentData[1] = componentData[2]
componentData[2] = temp
复制代码
同理,置顶置底也是同样,例如我要将 a 组件置顶,只需将 a 和最后一个组件调换顺序便可:
const temp = componentData[0]
componentData[0] = componentData[componentData.lenght - 1]
componentData[componentData.lenght - 1] = temp
复制代码
删除组件很是简单,一行代码搞定:componentData.splice(index, 1)
。
细心的网友可能会发现,点击画布上的组件时,组件上会出现 8 个小圆点。这 8 个小圆点就是用来放大缩小用的。实现原理以下:
Shape
组件,Shape
组件里包含 8 个小圆点和一个 <slot>
插槽,用于放置组件。<!--页面组件列表展现-->
<Shape v-for="(item, index) in componentData" :defaultStyle="item.style" :style="getShapeStyle(item.style, index)" :key="item.id" :active="item === curComponent" :element="item" :zIndex="index" >
<component class="component" :is="item.component" :style="getComponentStyle(item.style)" :propValue="item.propValue" />
</Shape>
复制代码
Shape
组件内部结构:
<template>
<div class="shape" :class="{ active: this.active }" @click="selectCurComponent" @mousedown="handleMouseDown" @contextmenu="handleContextMenu">
<div class="shape-point" v-for="(item, index) in (active? pointList : [])" @mousedown="handleMouseDownOnPoint(item)" :key="index" :style="getPointStyle(item)">
</div>
<slot></slot>
</div>
</template>
复制代码
起做用的是这行代码 :active="item === curComponent"
。
先来看一下计算小圆点位置的代码:
const pointList = ['t', 'r', 'b', 'l', 'lt', 'rt', 'lb', 'rb']
getPointStyle(point) {
const { width, height } = this.defaultStyle
const hasT = /t/.test(point)
const hasB = /b/.test(point)
const hasL = /l/.test(point)
const hasR = /r/.test(point)
let newLeft = 0
let newTop = 0
// 四个角的点
if (point.length === 2) {
newLeft = hasL? 0 : width
newTop = hasT? 0 : height
} else {
// 上下两点的点,宽度居中
if (hasT || hasB) {
newLeft = width / 2
newTop = hasT? 0 : height
}
// 左右两边的点,高度居中
if (hasL || hasR) {
newLeft = hasL? 0 : width
newTop = Math.floor(height / 2)
}
}
const style = {
marginLeft: hasR? '-4px' : '-3px',
marginTop: '-3px',
left: `${newLeft}px`,
top: `${newTop}px`,
cursor: point.split('').reverse().map(m => this.directionKey[m]).join('') + '-resize',
}
return style
}
复制代码
计算小圆点的位置须要获取一些信息:
height
、宽度 width
注意,小圆点也是绝对定位的,相对于 Shape
组件。因此有四个小圆点的位置很好肯定:
left: 0, top: 0
left: width, top: 0
left: 0, top: height
left: width, top: height
另外的四个小圆点须要经过计算间接算出来。例如左边中间的小圆点,计算公式为 left: 0, top: height / 2
,其余小圆点同理。
handleMouseDownOnPoint(point) {
const downEvent = window.event
downEvent.stopPropagation()
downEvent.preventDefault()
const pos = { ...this.defaultStyle }
const height = Number(pos.height)
const width = Number(pos.width)
const top = Number(pos.top)
const left = Number(pos.left)
const startX = downEvent.clientX
const startY = downEvent.clientY
// 是否须要保存快照
let needSave = false
const move = (moveEvent) => {
needSave = true
const currX = moveEvent.clientX
const currY = moveEvent.clientY
const disY = currY - startY
const disX = currX - startX
const hasT = /t/.test(point)
const hasB = /b/.test(point)
const hasL = /l/.test(point)
const hasR = /r/.test(point)
const newHeight = height + (hasT? -disY : hasB? disY : 0)
const newWidth = width + (hasL? -disX : hasR? disX : 0)
pos.height = newHeight > 0? newHeight : 0
pos.width = newWidth > 0? newWidth : 0
pos.left = left + (hasL? disX : 0)
pos.top = top + (hasT? disY : 0)
this.$store.commit('setShapeStyle', pos)
}
const up = () => {
document.removeEventListener('mousemove', move)
document.removeEventListener('mouseup', up)
needSave && this.$store.commit('recordSnapshot')
}
document.addEventListener('mousemove', move)
document.addEventListener('mouseup', up)
}
复制代码
它的原理是这样的:
撤销重作的实现原理其实挺简单的,先看一下代码:
snapshotData: [], // 编辑器快照数据
snapshotIndex: -1, // 快照索引
undo(state) {
if (state.snapshotIndex >= 0) {
state.snapshotIndex--
store.commit('setComponentData', deepCopy(state.snapshotData[state.snapshotIndex]))
}
},
redo(state) {
if (state.snapshotIndex < state.snapshotData.length - 1) {
state.snapshotIndex++
store.commit('setComponentData', deepCopy(state.snapshotData[state.snapshotIndex]))
}
},
setComponentData(state, componentData = []) {
Vue.set(state, 'componentData', componentData)
},
recordSnapshot(state) {
// 添加新的快照
state.snapshotData[++state.snapshotIndex] = deepCopy(state.componentData)
// 在 undo 过程当中,添加新的快照时,要将它后面的快照清理掉
if (state.snapshotIndex < state.snapshotData.length - 1) {
state.snapshotData = state.snapshotData.slice(0, state.snapshotIndex + 1)
}
},
复制代码
用一个数组来保存编辑器的快照数据。保存快照就是不停地执行 push()
操做,将当前的编辑器数据推入 snapshotData
数组,并增长快照索引 snapshotIndex
。目前如下几个动做会触发保存快照操做:
...
假设如今 snapshotData
保存了 4 个快照。即 [a, b, c, d]
,对应的快照索引为 3。若是这时进行了撤销操做,咱们须要将快照索引减 1,而后将对应的快照数据赋值给画布。
例如当前画布数据是 d,进行撤销后,索引 -1,如今画布的数据是 c。
明白了撤销,那重作就很好理解了,就是将快照索引加 1,而后将对应的快照数据赋值给画布。
不过还有一点要注意,就是在撤销操做中进行了新的操做,要怎么办呢?有两种解决方案:
[a, b, c, d]
举例,假设如今进行了两次撤销操做,快照索引变为 1,对应的快照数据为 b,若是这时进行了新的操做,对应的快照数据为 e。那 e 会把 cd 顶掉,如今的快照数据为 [a, b, e]
。[a, b, e, c, d]
。我采用的是第一种方案。
什么是吸附?就是在拖拽组件时,若是它和另外一个组件的距离比较接近,就会自动吸附在一块儿。
吸附的代码大概在 300 行左右,建议本身打开源码文件看(文件路径:src\components\Editor\MarkLine.vue
)。这里不贴代码了,主要说说原理是怎么实现的。
在页面上建立 6 条线,分别是三横三竖。这 6 条线的做用是对齐,它们何时会出现呢?
具体的计算公式主要是根据每一个组件的 xy 坐标和宽度高度进行计算的。例如要判断 ab 两个组件的左边是否对齐,则要知道它们每一个组件的 x 坐标;若是要知道它们右边是否对齐,除了要知道 x 坐标,还要知道它们各自的宽度。
// 左对齐的条件
a.x == b.x
// 右对齐的条件
a.x + a.width == b.x + b.width
复制代码
在对齐的时候,显示标线。
另外还要判断 ab 两个组件是否“足够”近。若是足够近,就吸附在一块儿。是否足够近要靠一个变量来判断:
diff: 3, // 相距 dff 像素将自动吸附
复制代码
小于等于 diff
像素则自动吸附。
吸附效果是怎么实现的呢?
假设如今有 ab 组件,a 组件坐标 xy 都是 0,宽高都是 100。如今假设 a 组件不动,咱们正在拖拽 b 组件。当把 b 组件拖到坐标为 x: 0, y: 103
时,因为 103 - 100 <= 3(diff)
,因此能够断定它们已经接近得足够近。这时须要手动将 b 组件的 y 坐标值设为 100,这样就将 ab 组件吸附在一块儿了。
在拖拽时若是 6 条标线都显示出来会不太美观。因此咱们能够作一下优化,在纵横方向上最多只同时显示一条线。实现原理以下:
能够发现,关键的地方是咱们要知道两个组件的方向。即 ab 两个组件靠近,咱们要知道到底 b 是在 a 的左边仍是右边。
这一点能够经过鼠标移动事件来判断,以前在讲解拖拽的时候说过,mousedown
事件触发时会记录起点坐标。因此每次触发 mousemove
事件时,用当前坐标减去原来的坐标,就能够判断组件方向。例如 x 方向上,若是 b.x - a.x
的差值为正,说明是 b 在 a 右边,不然为左边。
// 触发元素移动事件,用于显示标线、吸附功能
// 后面两个参数表明鼠标移动方向
// currY - startY > 0 true 表示向下移动 false 表示向上移动
// currX - startX > 0 true 表示向右移动 false 表示向左移动
eventBus.$emit('move', this.$el, currY - startY > 0, currX - startX > 0)
复制代码
每一个组件都有一些通用属性和独有的属性,咱们须要提供一个能显示和修改属性的地方。
// 每一个组件数据大概是这样
{
component: 'v-text', // 组件名称,须要提早注册到 Vue
label: '文字', // 左侧组件列表中显示的名字
propValue: '文字', // 组件所使用的值
icon: 'el-icon-edit', // 左侧组件列表中显示的名字
animations: [], // 动画列表
events: {}, // 事件列表
style: { // 组件样式
width: 200,
height: 33,
fontSize: 14,
fontWeight: 500,
lineHeight: '',
letterSpacing: 0,
textAlign: '',
color: '',
},
}
复制代码
我定义了一个 AttrList
组件,用于显示每一个组件的属性。
<template>
<div class="attr-list">
<el-form>
<el-form-item v-for="(key, index) in styleKeys" :key="index" :label="map[key]">
<el-color-picker v-if="key == 'borderColor'" v-model="curComponent.style[key]"></el-color-picker>
<el-color-picker v-else-if="key == 'color'" v-model="curComponent.style[key]"></el-color-picker>
<el-color-picker v-else-if="key == 'backgroundColor'" v-model="curComponent.style[key]"></el-color-picker>
<el-select v-else-if="key == 'textAlign'" v-model="curComponent.style[key]">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" ></el-option>
</el-select>
<el-input type="number" v-else v-model="curComponent.style[key]" />
</el-form-item>
<el-form-item label="内容" v-if="curComponent && curComponent.propValue && !excludes.includes(curComponent.component)">
<el-input type="textarea" v-model="curComponent.propValue" />
</el-form-item>
</el-form>
</div>
</template>
复制代码
代码逻辑很简单,就是遍历组件的 style
对象,将每个属性遍历出来。而且须要根据具体的属性用不一样的组件显示出来,例如颜色属性,须要用颜色选择器显示;数值类的属性须要用 type=number
的 input 组件显示等等。
为了方便用户修改属性值,我使用 v-model
将组件和值绑定在一块儿。
预览和编辑的渲染原理是同样的,区别是不须要编辑功能。因此只须要将原先渲染组件的代码稍微改一下就能够了。
<!--页面组件列表展现-->
<Shape v-for="(item, index) in componentData" :defaultStyle="item.style" :style="getShapeStyle(item.style, index)" :key="item.id" :active="item === curComponent" :element="item" :zIndex="index" >
<component class="component" :is="item.component" :style="getComponentStyle(item.style)" :propValue="item.propValue" />
</Shape>
复制代码
通过刚才的介绍,咱们知道 Shape
组件具有了拖拽、放大缩小的功能。如今只须要将 Shape
组件去掉,外面改为套一个普通的 DIV 就能够了(其实不用这个 DIV 也行,但为了绑定事件这个功能,因此须要加上)。
<!--页面组件列表展现-->
<div v-for="(item, index) in componentData" :key="item.id">
<component class="component" :is="item.component" :style="getComponentStyle(item.style)" :propValue="item.propValue" />
</div>
复制代码
保存代码的功能也特别简单,只须要保存画布上的数据 componentData
便可。保存有两种选择:
在 DEMO 上我使用的 localStorage
保存在本地。
每一个组件有一个 events
对象,用于存储绑定的事件。目前我只定义了两个事件:
// 编辑器自定义事件
const events = {
redirect(url) {
if (url) {
window.location.href = url
}
},
alert(msg) {
if (msg) {
alert(msg)
}
},
}
const mixins = {
methods: events,
}
const eventList = [
{
key: 'redirect',
label: '跳转事件',
event: events.redirect,
param: '',
},
{
key: 'alert',
label: 'alert 事件',
event: events.alert,
param: '',
},
]
export {
mixins,
events,
eventList,
}
复制代码
不过不能在编辑的时候触发,能够在预览的时候触发。
经过 v-for
指令将事件列表渲染出来:
<el-tabs v-model="eventActiveName">
<el-tab-pane v-for="item in eventList" :key="item.key" :label="item.label" :name="item.key" style="padding: 0 20px">
<el-input v-if="item.key == 'redirect'" v-model="item.param" type="textarea" placeholder="请输入完整的 URL" />
<el-input v-if="item.key == 'alert'" v-model="item.param" type="textarea" placeholder="请输入要 alert 的内容" />
<el-button style="margin-top: 20px;" @click="addEvent(item.key, item.param)">肯定</el-button>
</el-tab-pane>
</el-tabs>
复制代码
选中事件时将事件添加到组件的 events
对象。
预览或真正渲染页面时,也须要在每一个组件外面套一层 DIV,这样就能够在 DIV 上绑定一个点击事件,点击时触发咱们刚才添加的事件。
<template>
<div @click="handleClick">
<component class="conponent" :is="config.component" :style="getStyle(config.style)" :propValue="config.propValue" />
</div>
</template>
复制代码
handleClick() {
const events = this.config.events
// 循环触发绑定的事件
Object.keys(events).forEach(event => {
this[event](events[event])
})
}
复制代码
动画和事件的原理是同样的,先将全部的动画经过 v-for
指令渲染出来,而后点击动画将对应的动画添加到组件的 animations
数组里。同事件同样,执行的时候也是遍历组件全部的动画并执行。
为了方便,咱们使用了 animate.css 动画库。
// main.js
import '@/styles/animate.css'
复制代码
如今咱们提早定义好全部的动画数据:
export default [
{
label: '进入',
children: [
{ label: '渐显', value: 'fadeIn' },
{ label: '向右进入', value: 'fadeInLeft' },
{ label: '向左进入', value: 'fadeInRight' },
{ label: '向上进入', value: 'fadeInUp' },
{ label: '向下进入', value: 'fadeInDown' },
{ label: '向右长距进入', value: 'fadeInLeftBig' },
{ label: '向左长距进入', value: 'fadeInRightBig' },
{ label: '向上长距进入', value: 'fadeInUpBig' },
{ label: '向下长距进入', value: 'fadeInDownBig' },
{ label: '旋转进入', value: 'rotateIn' },
{ label: '左顺时针旋转', value: 'rotateInDownLeft' },
{ label: '右逆时针旋转', value: 'rotateInDownRight' },
{ label: '左逆时针旋转', value: 'rotateInUpLeft' },
{ label: '右逆时针旋转', value: 'rotateInUpRight' },
{ label: '弹入', value: 'bounceIn' },
{ label: '向右弹入', value: 'bounceInLeft' },
{ label: '向左弹入', value: 'bounceInRight' },
{ label: '向上弹入', value: 'bounceInUp' },
{ label: '向下弹入', value: 'bounceInDown' },
{ label: '光速从右进入', value: 'lightSpeedInRight' },
{ label: '光速从左进入', value: 'lightSpeedInLeft' },
{ label: '光速从右退出', value: 'lightSpeedOutRight' },
{ label: '光速从左退出', value: 'lightSpeedOutLeft' },
{ label: 'Y轴旋转', value: 'flip' },
{ label: '中心X轴旋转', value: 'flipInX' },
{ label: '中心Y轴旋转', value: 'flipInY' },
{ label: '左长半径旋转', value: 'rollIn' },
{ label: '由小变大进入', value: 'zoomIn' },
{ label: '左变大进入', value: 'zoomInLeft' },
{ label: '右变大进入', value: 'zoomInRight' },
{ label: '向上变大进入', value: 'zoomInUp' },
{ label: '向下变大进入', value: 'zoomInDown' },
{ label: '向右滑动展开', value: 'slideInLeft' },
{ label: '向左滑动展开', value: 'slideInRight' },
{ label: '向上滑动展开', value: 'slideInUp' },
{ label: '向下滑动展开', value: 'slideInDown' },
],
},
{
label: '强调',
children: [
{ label: '弹跳', value: 'bounce' },
{ label: '闪烁', value: 'flash' },
{ label: '放大缩小', value: 'pulse' },
{ label: '放大缩小弹簧', value: 'rubberBand' },
{ label: '左右晃动', value: 'headShake' },
{ label: '左右扇形摇摆', value: 'swing' },
{ label: '放大晃动缩小', value: 'tada' },
{ label: '扇形摇摆', value: 'wobble' },
{ label: '左右上下晃动', value: 'jello' },
{ label: 'Y轴旋转', value: 'flip' },
],
},
{
label: '退出',
children: [
{ label: '渐隐', value: 'fadeOut' },
{ label: '向左退出', value: 'fadeOutLeft' },
{ label: '向右退出', value: 'fadeOutRight' },
{ label: '向上退出', value: 'fadeOutUp' },
{ label: '向下退出', value: 'fadeOutDown' },
{ label: '向左长距退出', value: 'fadeOutLeftBig' },
{ label: '向右长距退出', value: 'fadeOutRightBig' },
{ label: '向上长距退出', value: 'fadeOutUpBig' },
{ label: '向下长距退出', value: 'fadeOutDownBig' },
{ label: '旋转退出', value: 'rotateOut' },
{ label: '左顺时针旋转', value: 'rotateOutDownLeft' },
{ label: '右逆时针旋转', value: 'rotateOutDownRight' },
{ label: '左逆时针旋转', value: 'rotateOutUpLeft' },
{ label: '右逆时针旋转', value: 'rotateOutUpRight' },
{ label: '弹出', value: 'bounceOut' },
{ label: '向左弹出', value: 'bounceOutLeft' },
{ label: '向右弹出', value: 'bounceOutRight' },
{ label: '向上弹出', value: 'bounceOutUp' },
{ label: '向下弹出', value: 'bounceOutDown' },
{ label: '中心X轴旋转', value: 'flipOutX' },
{ label: '中心Y轴旋转', value: 'flipOutY' },
{ label: '左长半径旋转', value: 'rollOut' },
{ label: '由小变大退出', value: 'zoomOut' },
{ label: '左变大退出', value: 'zoomOutLeft' },
{ label: '右变大退出', value: 'zoomOutRight' },
{ label: '向上变大退出', value: 'zoomOutUp' },
{ label: '向下变大退出', value: 'zoomOutDown' },
{ label: '向左滑动收起', value: 'slideOutLeft' },
{ label: '向右滑动收起', value: 'slideOutRight' },
{ label: '向上滑动收起', value: 'slideOutUp' },
{ label: '向下滑动收起', value: 'slideOutDown' },
],
},
]
复制代码
而后用 v-for
指令渲染出来动画列表。
<el-tabs v-model="animationActiveName">
<el-tab-pane v-for="item in animationClassData" :key="item.label" :label="item.label" :name="item.label">
<el-scrollbar class="animate-container">
<div class="animate" v-for="(animate, index) in item.children" :key="index" @mouseover="hoverPreviewAnimate = animate.value" @click="addAnimation(animate)" >
<div :class="[hoverPreviewAnimate === animate.value && animate.value + ' animated']">
{{ animate.label }}
</div>
</div>
</el-scrollbar>
</el-tab-pane>
</el-tabs>
复制代码
点击动画将调用 addAnimation(animate)
将动画添加到组件的 animations
数组。
运行动画的代码:
export default async function runAnimation($el, animations = []) {
const play = (animation) => new Promise(resolve => {
$el.classList.add(animation.value, 'animated')
const removeAnimation = () => {
$el.removeEventListener('animationend', removeAnimation)
$el.removeEventListener('animationcancel', removeAnimation)
$el.classList.remove(animation.value, 'animated')
resolve()
}
$el.addEventListener('animationend', removeAnimation)
$el.addEventListener('animationcancel', removeAnimation)
})
for (let i = 0, len = animations.length; i < len; i++) {
await play(animations[i])
}
}
复制代码
运行动画须要两个参数:组件对应的 DOM 元素(在组件使用 this.$el
获取)和它的动画数据 animations
。而且须要监听 animationend
事件和 animationcancel
事件:一个是动画结束时触发,一个是动画意外终止时触发。
利用这一点再配合 Promise
一块儿使用,就能够逐个运行组件的每一个动画了。
因为时间关系,这个功能我还没作。如今简单的描述一下怎么作这个功能。那就是使用 psd.js 库,它能够解析 PSD 文件。
使用 psd
库解析 PSD 文件得出的数据以下:
{ children:
[ { type: 'group',
visible: false,
opacity: 1,
blendingMode: 'normal',
name: 'Version D',
left: 0,
right: 900,
top: 0,
bottom: 600,
height: 600,
width: 900,
children:
[ { type: 'layer',
visible: true,
opacity: 1,
blendingMode: 'normal',
name: 'Make a change and save.',
left: 275,
right: 636,
top: 435,
bottom: 466,
height: 31,
width: 361,
mask: {},
text:
{ value: 'Make a change and save.',
font:
{ name: 'HelveticaNeue-Light',
sizes: [ 33 ],
colors: [ [ 85, 96, 110, 255 ] ],
alignment: [ 'center' ] },
left: 0,
top: 0,
right: 0,
bottom: 0,
transform: { xx: 1, xy: 0, yx: 0, yy: 1, tx: 456, ty: 459 } },
image: {} } ] } ],
document:
{ width: 900,
height: 600,
resources:
{ layerComps:
[ { id: 692243163, name: 'Version A', capturedInfo: 1 },
{ id: 725235304, name: 'Version B', capturedInfo: 1 },
{ id: 730932877, name: 'Version C', capturedInfo: 1 } ],
guides: [],
slices: [] } } }
复制代码
从以上代码能够发现,这些数据和 css 很是像。根据这一点,只须要写一个转换函数,将这些数据转换成咱们组件所需的数据,就能实现 PSD 文件转成渲染组件的功能。目前 quark-h5 和 luban-h5 都是这样实现的 PSD 转换功能。
因为画布是能够调整大小的,咱们可使用 iphone6 的分辨率来开发手机页面。
这样开发出来的页面也能够在手机下正常浏览,但可能会有样式误差。由于我自定义的三个组件是没有作适配的,若是你须要开发手机页面,那自定义组件必须使用移动端的 UI 组件库。或者本身开发移动端专用的自定义组件。
因为 DEMO 的代码比较多,因此在讲解每个功能点时,我只把关键代码贴上来。因此你们会发现 DEMO 的源码和我贴上来的代码会有些区别,请没必要在乎。
另外,DEMO 的样式也比较简陋,主要是最近事情比较多,没太多时间写好看点,请见谅。
可视化拖拽系列文章: