微信小程序内拖动图片实现移动、放大、旋转

    最近接到一个任务,在微信小程序内拖动图片组件实现移动、放大、旋转,并记录这些图片的移动位置,放大比例,旋转角度,在一个画布上生成一张图片,最后保存到手机相册。

    我的具体实现思路是这样的:

    一共三个功能,可以先把功能分为图片 拖动 和图片 旋转缩放 , 把图片的缩放和旋转做在了一起。

    1.图片移动:可移动的图片肯定是要动态生成的,所以不能写死,应该是个数组,具备很多的属性。

 
 
itemList : [{
id : 1 ,
image : '1.png' ,//图片地址
top : 100 ,//初始图片的位置
left : 100 ,
x : 155 , //初始圆心位置,可再downImg之后又宽高和初始的图片位置得出
y : 155 ,
scale : 1 ,//缩放比例 1为不缩放
angle : 0 ,//旋转角度
active : false //判定点击状态
}, {
id : 2 ,
image : '2.png' ,
top : 50 ,
left : 50 ,
x : 155 ,
y : 155 ,
scale : 1 ,
angle : 0 ,
active : false
}]

事件绑定图片上或者图片的父级,绑定bindtouchstart  bindtouchmove事件。再bindtouchstart事件里,获取手指点击的某一个图片的点击坐标,并记录在这个图片对象的属性里面,在bindtouchmove事件里,移动的时候记录移动后的坐标,并算出俩次滑动的距离差值,追加给图片对象的left、top、x、y上,最后把本次滑动的坐标赋值给bindtouchmove事件里拿到的坐标,作为老坐标。这样就可以实现图片的滑动。

 
 
WraptouchStart : function (e ) {
for ( let i = 0 ; i < items .length ; i ++) { //旋转数据找到点击的
items [i ].active = false ;
if (e .currentTarget .dataset .id == items [i ].id ) {
index = i ; //记录下标
items [index ].active = true ; //开启点击属性
}
}
items [index ].lx = e .touches [ 0 ].clientX ; // 记录点击时的坐标值
items [index ].ly = e .touches [ 0 ].clientY ;
        this .setData ({ //赋值
itemList : items
})
}
, WraptouchMove : function (e ) {
        //移动时的坐标值也写图片的属性里
items [index ]._lx = e .touches [ 0 ].clientX ;
items [index ]._ly = e .touches [ 0 ].clientY ;
        
        //追加改动值
items [index ].left += items [index ]._lx - items [index ].lx ; // x方向
items [index ].top += items [index ]._ly - items [index ].ly ; // y方向
items [index ].x + = items [index ]._lx - items [index ].lx ;
items [index ].y + = items [index ]._ly - items [index ].ly ;
        
        //把新的值赋给老的值
items [index ].lx = e .touches [ 0 ].clientX ;
items [index ].ly = e .touches [ 0 ].clientY ;
this .setData ({//赋值就移动了
itemList : items
})
}

    

猜你喜欢

转载自blog.csdn.net/qq_37942845/article/details/80169907
今日推荐