cropping.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. function getRoundedCanvas(sourceCanvas) {
  2. var canvas = document.createElement('canvas');
  3. var context = canvas.getContext('2d');
  4. var width = sourceCanvas.width;
  5. var height = sourceCanvas.height;
  6. canvas.width = width;
  7. canvas.height = height;
  8. context.imageSmoothingEnabled = true;
  9. context.drawImage(sourceCanvas, 0, 0, width, height);
  10. context.globalCompositeOperation = 'destination-in';
  11. context.beginPath();
  12. context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
  13. context.fill();
  14. return canvas;
  15. }
  16. var input = document.getElementById('form_avatar')
  17. var container = document.getElementById('img-container')
  18. var cropImage = document.getElementById('img-cropped')
  19. var cropped = document.getElementById('form_hidden')
  20. input.addEventListener('change', function (e) {
  21. if (!input.files || !input.files[0]) return;
  22. var reader = new FileReader()
  23. reader.onload = function (e) {
  24. container.style = 'display: block'
  25. cropImage.setAttribute('src', e.target.result)
  26. function update() {
  27. var croppedCanvas = cropper.getCroppedCanvas()
  28. var roundedCanvas = getRoundedCanvas(croppedCanvas)
  29. cropped.value = roundedCanvas.toDataURL()
  30. input.files = undefined
  31. }
  32. var cropper = new Cropper(cropImage, {
  33. aspectRatio: 1,
  34. viewMode: 1,
  35. cropend: update,
  36. ready: update,
  37. })
  38. }
  39. reader.readAsDataURL(input.files[0])
  40. })