<script setup>
import { reactive, computed } from 'vue'
import dynamics from 'https://cdn.skypack.dev/dynamics.js'
const headerHeight = 120
let isDragging = false
const start = { x: 0, y: 0 }
const c = ref({ x: headerHeight, y: headerHeight })
// svg是基于XML语法的图像格式,全称:Scalable Vector Graphics,即可缩放矢量图。
// 参考:https://blog.csdn.net/seevc/article/details/132669663
// svg路径起始点绘制
// M命令,moveto缩写,表示绘制的起点坐标
// L命令,lineto的缩写,表示绘制一条直线,如:L50,10,表示从上一个结束点到(50,10)绘制一条直线;
// Q命令,绘制二次贝塞尔曲线,要定义控制点和终点坐标,如:Q150,-300 300,0,表示控制点是(150,-300),终点坐标(300,0)
// 动态修改Q命令中的控制点坐标
const headerPath = computed(() => {
//从(0,0)坐标作为绘制起点坐标,直线左侧起始点(0,640),右侧终点(640,120),坐标形式(x,y),水平方向为x坐标,垂直方向为y坐标
//贝塞尔曲线控制点为动态值(c.x,c.y),终点为(0,120)
return `M0,0 L640,0 640,${headerHeight}Q${c.x},${c.y} 0,${headerHeight}`
})
const contentPosition = computed(() => {
const dy = c.y - headerHeight
const dampen = dy > 0 ? 2 : 4
return {
transform: `translate(0,${dy / dampen}px)`
}
})
function startDrag(e) {
e = e.changedTouches ? e.changedTouches[0] : e
isDragging = true
start.x = e.pageX
start.y = e.pageY
}
function onDrag(e) {
e = e.changedTouches ? e.changedTouches[0] : e
if (isDragging) {
c.x = headerHeight + (e.pageX - start.x)
const dy = e.pageY - start.y
const dampen = dy > 0 ? 1.5 : 4
c.y = headerHeight + dy / dampen
}
}
function stopDrag() {
if (isDragging) {
isDragging = false
dynamics.animate(
c,
{ x: headerHeight, y: headerHeight },
{ type: dynamics.spring, duration: 700, friction: 280 }
)
}
}
</script>
<template>
<div class="draggable" @mousedown="startDrag" @mousemove="onDrag" @mouseup="stopDrag" @mouseleave="stopDrag"
@touchstart="startDrag" @touchmove="onDrag" @touchend="stopDrag" >
<svg class="bg" width="640" height="560">
<path :d="headerPath" fill="#3F51B5"></path>
</svg>
<div class="header">Drag Me</div>
<div class="content" :style="contentPosition">Hello</div>
</div>
</template>
<style scoped>
.draggable {
background-color: #fff;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
width: 640px;
height: 480px;
overflow: hidden;
margin: 30px auto;
position: relative;
text-align: center;
font-size: 14px;
font-weight: 300;
user-select: none;
border-radius: 8px;
}
.bg {
position: absolute;
top: 0;
left: 0;
z-index: 0;
}
.header,
.content {
position: relative;
z-index: 1;
padding: 30px;
box-sizing: border-box;
}
.header {
color: #fff;
height: 120px;
font-size: 2em;
font-weight: bold;
}
</style>
Vue3实现SVG矢量图绘制拖拽效果
于 2024-06-04 15:54:11 首次发布