User:BrandonXLF/CSSImageCrop.js

/*** CSS Image Crop ***/

// A utility to use {{CSS image crop}} to crop an image

// Documentation at en:w:User:BrandonXLF/CSSImageCrop

// By en:w:User:BrandonXLF

$(function() {

var sampleImg = 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Dew_on_grass_Luc_Viatour.jpg/1920px-Dew_on_grass_Luc_Viatour.jpg';

mw.util.addPortletLink('p-tb', mw.util.getUrl('Special:BlankPage/CSSImageCrop'), 'CSS image crop');

function clamp(min, x, max) {

return Math.min(max, Math.max(min, x));

}

function update() {

var mult = img.width() / size.val(),

mult2 = size.val() / img.width();

area.css({

left: clamp(0, left.val(), (parent.width() * mult2) - parseInt(area.css('right'))) * mult + 'px',

top: clamp(0, top.val(), (parent.height() * mult2) - parseInt(area.css('bottom'))) * mult + 'px',

right: clamp(0, (parent.width() * mult2) - width.val() - left.val(), (parent.width() * mult2) - parseInt(area.css('left'))) * mult + 'px',

bottom: clamp(0, (parent.height() * mult2) - height.val() - top.val(), (parent.height() * mult2) - parseInt(area.css('top'))) * mult + 'px'

});

setCode();

}

function setCode() {

var mult = size.val() / img.width();

width.val(Math.round(area.width() * mult));

height.val(Math.round(area.height() * mult));

left.val(Math.round(area.position().left * mult));

top.val(Math.round(area.position().top * mult));

makeCode();

}

function makeCode() {

textarea.val(

'{{CSS image crop\n' +

'|Image = ' + file.val() + '\n' +

'|bSize = ' + size.val() + '\n' +

'|cWidth = ' + width.val() + '\n' +

'|cHeight = ' + height.val() + '\n' +

'|oLeft = ' + left.val() + '\n' +

'|oTop = ' + top.val() + '\n' +

(location.val() ? '|Location = ' + location.val() + '\n' : '') +

(desc.val() ? '|Description = ' + desc.val() + '\n' : '') +

'}}'

);

}

function repos(ele, func) {

ele.on('mousedown', function(e) {

e.stopPropagation();

function move(e) {

func(e);

setCode();

}

function up() {

$(document.body).off('mousemove', move);

$(document.body).off('mouseup', up);

}

$(document.body).on('mousemove', move);

$(document.body).on('mouseup', up);

});

}

var parent = $('

'),

area = $('

'),

img = $('').on('load', function() {

if (!$('#img').attr('data-loaded')) {

$('#img').attr('data-loaded', 'true');

return;

}

$('#img').width($('#img').get(0).naturalWidth);

size.val($('#img').get(0).naturalWidth);

}),

north = $('

'),

south = $('

'),

east = $('

'),

west = $('

'),

file = $('').on('change', function() {

img.attr('src', 'https://en.wikipedia.org/wiki/Special:Filepath/' + file.val());

}),

size = $('').on('change', setCode),

textarea = $('