How to realize the drag and cut effect of uploading avatar on mobile terminal by canvas in HTML5
This article will explain in detail how canvas implements the drag and cut effect of uploading avatars on mobile devices in HTML5. The editor finds it very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Html section:
Upload avatar
Save
The following is a cut picture:
JavaScript section:
JavaScript Code copies content to the clipboard
Var $imgCrop = $("# imgCrop")
Var $img = $imgCrop.find ("img")
Var img = $img [0]
Var width = parseInt ($imgCrop.css ("width"))
Var height = parseInt ($imgCrop.css ("height"))
Var startX,startY,scale = 1
Var x = 0BI y = 0
$("input") .on ("change", function () {
Var fr = new FileReader ()
Var file = this.files [0]
/ / console.log (file)
If (! / image///w+/.test (file.type)) {
Alert (file.name + "not a picture file!")
Return
}
Console.log (file)
$img.removeAttr ("height width")
Fr.readAsDataURL (file)
Fr.onload = function () {
Img.src = fr.result
Var widthInit = img.width
If (img.width > img.height) {
Img.height = height
X = (width-img.width) / 2
Y = 0
} else {
Img.width = width
X = 0
Y = (height-img.height) / 2
}
Scale = widthInit/img.width
Move ($img, x, y)
}
});
Img.addEventListener ("touchstart", function (e) {
StartX = e.targetTouches [0] .pageX
StartY = e.targetTouches [0] .pageY
Return
});
Img.addEventListener ("touchmove", function (e) {
E.preventDefault ()
E.stopPropagation ()
Var changeX = e.changedTouches [0] .pageX-startX + x
Var changeY = e.changedTouches [0] .pageY-startY + y
Move ($(this), changeX, changeY)
Return
});
Img.addEventListener ("touchend", function (e) {
Var changeX = e.changedTouches [0] .pageX-startX + x
Var changeY = e.changedTouches [0] .pageY-startY + y
X = x + e.changedTouches [0] .pageX-startX
Y = y + e.changedTouches [0] .pageY-startY
Move ($(this), changeX, changeY)
Return
});
/ / determine the style of the target picture
Function move (ele, x, y) {
Ele.css ({
'- webkit-transform':' translate3d ('+ x +'px,'+ y +'px, 0)'
'transform':' translate3d ('+ x +'px,'+ y +'px, 0)'
});
}
$("# save"). On ("click", function () {
Var url = imageData ($img)
Console.log (url)
("# imgShow") .html ("
")
});
/ / crop the picture
Function imageData ($img) {
Var canvas = document.createElement ('canvas')
Var ctx = canvas.getContext ('2d')
Canvas.width = width
Canvas.height = height
Ctx.drawImage (img,-x*scale,-y*scale, width*scale, height*scale, 0,0, width, height)
Return canvas.toDataURL ()
}
This is the end of the article on "how to achieve the drag and cut effect of uploading avatars on mobile in canvas in HTML5". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.