[JS][UI][AVATAR] JS cropping script

This commit is contained in:
rainydaysavings 2020-08-05 19:07:38 +01:00 committed by Hugo Sales
parent 774383a3c1
commit d717aac67f
Signed by untrusted user: someonewithpc
GPG Key ID: 7D0C7EAFC9D835A0
2 changed files with 48 additions and 0 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "public/assets/javascript/cropperjs"]
path = public/assets/javascript/cropperjs
url = https://github.com/fengyuanchen/cropperjs.git

View File

@ -0,0 +1,45 @@
function getRoundedCanvas(sourceCanvas) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var width = sourceCanvas.width;
var height = sourceCanvas.height;
canvas.width = width;
canvas.height = height;
context.imageSmoothingEnabled = true;
context.drawImage(sourceCanvas, 0, 0, width, height);
context.globalCompositeOperation = 'destination-in';
context.beginPath();
context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
context.fill();
return canvas;
}
var input = document.getElementById('form_avatar')
var container = document.getElementById('img-container')
var cropImage = document.getElementById('img-cropped')
var cropped = document.getElementById('form_hidden')
input.addEventListener('change', function (e) {
if (!input.files || !input.files[0]) return;
var reader = new FileReader()
reader.onload = function (e) {
container.style = 'display: block'
cropImage.setAttribute('src', e.target.result)
function update() {
var croppedCanvas = cropper.getCroppedCanvas()
var roundedCanvas = getRoundedCanvas(croppedCanvas)
cropped.value = roundedCanvas.toDataURL()
input.files = undefined
}
var cropper = new Cropper(cropImage, {
aspectRatio: 1,
viewMode: 1,
cropend: update,
ready: update,
})
}
reader.readAsDataURL(input.files[0])
})