直接上代码
handleScale() {
const store = {
scale: 1,
}
const start = {
x: 0,
y: 0,
}
const position = {
top: 0,
left: 0,
}
document.addEventListener('touchmove', function (event) {
// mavonEditor的图片预览会生成一个v-note-img-wrapper元素,里面有个img元素, 主要是控制这个缩放和移动
const eleImg = document.getElementsByClassName('v-note-img-wrapper')[0]?.getElementsByTagName('img')[0]
if (!eleImg) {
return
}
// 阻止滚动链传递
document.body.style.position = 'relative'
document.body.style.overflow = 'hidden'
// 元素移动
eleImg.addEventListener('touchmove', function (e) {
e.preventDefault()
const touches = e.touches
if (touches.length === 1) {
if (start.x === 0 && start.y === 0) {
start.x = touches[0].clientX
start.y = touches[0].clientY
}
eleImg.style.position = 'relative'
position.top += touches[0].clientY - start.y
position.left += touches[0].clientX - start.x
eleImg.style.left = `${position.left}px`
eleImg.style.top = `${position.top}px`
start.x = touches[0].clientX
start.y = touches[0].clientY
}
})
// 缩放事件的处理
eleImg.addEventListener('touchstart', function (event) {
const touches = event.touches
const events = touches[0]
const events2 = touches[1]
// event.preventDefault()
start.x = events.clientX
start.y = events.clientY
// 第一个触摸点的坐标
store.pageX = events.pageX
store.pageY = events.pageY
// store.moveable = true
if (events2) {
store.pageX2 = events2.pageX
store.pageY2 = events2.pageY
}
store.originScale = store.scale || 1
})
//event.preventDefault() // iphone预览状态下点击图片不能点击图片关闭预览模式, 所以这里不能阻止默认行为
const touches = event.touches
const events = touches[0]
const events2 = touches[1]
// 双指移动
if (events2) {
// 第2个指头坐标在touchmove时候获取
if (!store.pageX2) {
store.pageX2 = events2.pageX
}
if (!store.pageY2) {
store.pageY2 = events2.pageY
}
// 获取坐标之间的举例
const getDistance = function (start, stop) {
return Math.hypot(stop.x - start.x, stop.y - start.y)
}
// 双指缩放比例计算
const zoom =
getDistance(
{
x: events.pageX,
y: events.pageY,
},
{
x: events2.pageX,
y: events2.pageY,
}
) /
getDistance(
{
x: store.pageX,
y: store.pageY,
},
{
x: store.pageX2,
y: store.pageY2,
}
)
// 应用在元素上的缩放比例
let newScale = store.originScale * zoom
// 最大缩放比例限制
if (newScale > 2) {
newScale = 2
}
if (newScale < 1) {
newScale = 1
}
// 记住使用的缩放值
store.scale = newScale
// 图像应用缩放效果
eleImg.style.transform = 'scale(' + newScale + ')'
}
})
document.addEventListener('touchend', function () {
document.body.style.position = ''
document.body.style.overflow = ''
// store.moveable = false
delete store.pageX2
delete store.pageY2
})
document.addEventListener('touchcancel', function () {
document.body.style.position = ''
document.body.style.overflow = ''
// store.moveable = false
delete store.pageX2
delete store.pageY2
})
},