Recently received a task, drag the picture component in the WeChat applet to realize the movement, enlargement and rotation, and record the moving position, enlargement ratio and rotation angle of these pictures, generate a picture on a canvas, and finally save it to the mobile phone album .
My specific implementation idea is as follows:
There are a total of three functions, you can first divide the functions into picture drag and picture rotation and zoom , and make the picture zoom and rotation together.
1. Picture movement : The movable picture must be dynamically generated, so it cannot be written to death. It should be an array with many attributes.
itemList
:
[{
id
:
1,
image
:
'1.png'
,//image address
top
:
100
,//The position of the initial image
left
:
100
,
x
:
155
, //The initial circle center position can be obtained after downImg and the width and height and the initial picture position
and
:
155
,
scale
:
1
,//The scaling ratio 1 is no scaling
angle
:
0
,//rotation angle
active
:
false //Determine the click state
},
{
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
})
}