ui.avatar_cropper.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Avatar cropping
  3. */
  4. elgg.provide('elgg.avatarCropper');
  5. /**
  6. * Register the avatar cropper.
  7. *
  8. * If the hidden inputs have the coordinates from a previous cropping, begin
  9. * the selection and preview with that displayed.
  10. */
  11. elgg.avatarCropper.init = function() {
  12. var params = {
  13. selectionOpacity: 0,
  14. aspectRatio: '1:1',
  15. onSelectEnd: elgg.avatarCropper.selectChange,
  16. onSelectChange: elgg.avatarCropper.preview
  17. };
  18. if ($('input[name=x2]').val()) {
  19. params.x1 = $('input[name=x1]').val();
  20. params.x2 = $('input[name=x2]').val();
  21. params.y1 = $('input[name=y1]').val();
  22. params.y2 = $('input[name=y2]').val();
  23. }
  24. $('#user-avatar-cropper').imgAreaSelect(params);
  25. if ($('input[name=x2]').val()) {
  26. // TODO figure out why this is necessary
  27. $(window).on('load', function () {
  28. var ias = $('#user-avatar-cropper').imgAreaSelect({instance: true});
  29. var selection = ias.getSelection();
  30. elgg.avatarCropper.preview($('#user-avatar-cropper'), selection);
  31. });
  32. }
  33. };
  34. /**
  35. * Handler for changing select area.
  36. *
  37. * @param {Object} img reference to the image
  38. * @param {Object} selection imgareaselect selection object
  39. * @return void
  40. */
  41. elgg.avatarCropper.preview = function(img, selection) {
  42. // catch for the first click on the image
  43. if (selection.width === 0 || selection.height === 0) {
  44. return;
  45. }
  46. var origWidth = $("#user-avatar-cropper").width();
  47. var origHeight = $("#user-avatar-cropper").height();
  48. var scaleX = 100 / selection.width;
  49. var scaleY = 100 / selection.height;
  50. $('#user-avatar-preview > img').css({
  51. width: Math.round(scaleX * origWidth) + 'px',
  52. height: Math.round(scaleY * origHeight) + 'px',
  53. marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
  54. marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
  55. });
  56. };
  57. /**
  58. * Handler for updating the form inputs after select ends
  59. *
  60. * @param {Object} img reference to the image
  61. * @param {Object} selection imgareaselect selection object
  62. * @return void
  63. */
  64. elgg.avatarCropper.selectChange = function(img, selection) {
  65. $('input[name=x1]').val(selection.x1);
  66. $('input[name=x2]').val(selection.x2);
  67. $('input[name=y1]').val(selection.y1);
  68. $('input[name=y2]').val(selection.y2);
  69. };
  70. elgg.register_hook_handler('init', 'system', elgg.avatarCropper.init);