aboutsummaryrefslogtreecommitdiff
path: root/js/lib/avatar_cropper.js
blob: df6ba78660584534e3161f48f93915c5da491700 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
 * Avatar cropping
 */

elgg.provide('elgg.avatarCropper');

/**
 * Register the avatar cropper.
 *
 * If the hidden inputs have the coordinates from a previous cropping, begin
 * the selection and preview with that displayed.
 */
elgg.avatarCropper.init = function() {
	var params = {
		selectionOpacity: 0,
		aspectRatio: '1:1',
		onSelectEnd: elgg.avatarCropper.selectChange,
		onSelectChange: elgg.avatarCropper.preview
	};

	if ($('input[name=x2]').val()) {
		params.x1 = $('input[name=x1]').val();
		params.x2 = $('input[name=x2]').val();
		params.y1 = $('input[name=y1]').val();
		params.y2 = $('input[name=y2]').val();
	}

	$('#user-avatar-cropper').imgAreaSelect(params);

	if ($('input[name=x2]').val()) {
		var ias = $('#user-avatar-cropper').imgAreaSelect({instance: true});
		var selection = ias.getSelection();
		elgg.avatarCropper.preview($('#user-avatar-cropper'), selection);
	}
}

/**
 * Handler for changing select area.
 *
 * @param {Object} reference to the image
 * @param {Object} imgareaselect selection object
 * @return void
 */
elgg.avatarCropper.preview = function(img, selection) {
	// catch for the first click on the image
	if (selection.width == 0 || selection.height == 0) {
		return;
	}

	var origWidth = $("#user-avatar-cropper").width();
	var origHeight = $("#user-avatar-cropper").height();
	var scaleX = 100 / selection.width;
	var scaleY = 100 / selection.height;
	$('#user-avatar-preview > img').css({
		width: Math.round(scaleX * origWidth) + 'px',
		height: Math.round(scaleY * origHeight) + 'px',
		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
	});
}

/**
 * Handler for updating the form inputs after select ends
 *
 * @param {Object} reference to the image
 * @param {Object} imgareaselect selection object
 * @return void
 */
elgg.avatarCropper.selectChange = function(img, selection) {
	$('input[name=x1]').val(selection.x1);
	$('input[name=x2]').val(selection.x2);
	$('input[name=y1]').val(selection.y1);
	$('input[name=y2]').val(selection.y2);
}

elgg.register_hook_handler('init', 'system', elgg.avatarCropper.init);