Commit 0af02764 authored by Pradyuman Mishra's avatar Pradyuman Mishra

Merge branch 'develop' of http://silos.incaendo.com/hanumant/coconva2118 into develop

parents 08d040b0 3b8e7747
...@@ -36,6 +36,7 @@ $tabStyle = $_config->getProductDetail('tab_style'); ...@@ -36,6 +36,7 @@ $tabStyle = $_config->getProductDetail('tab_style');
jQuery('#product_addtocart_form #select_3 option, #product_addtocart_form #select_2 option, #product_addtocart_form #select_4 option').each(function(){ jQuery('#product_addtocart_form #select_3 option, #product_addtocart_form #select_2 option, #product_addtocart_form #select_4 option').each(function(){
var $this = $(this); var $this = $(this);
var value = $this.text().trim(); var value = $this.text().trim();
var percent = parseInt(config[value.split(' ')[0]]); var percent = parseInt(config[value.split(' ')[0]]);
console.log("------------------------", `==${value}==`, percent, config, config[value], baseHeight, baseWidth); console.log("------------------------", `==${value}==`, percent, config, config[value], baseHeight, baseWidth);
if (percent && percent > 0) { if (percent && percent > 0) {
...@@ -44,18 +45,276 @@ $tabStyle = $_config->getProductDetail('tab_style'); ...@@ -44,18 +45,276 @@ $tabStyle = $_config->getProductDetail('tab_style');
$this.text(`${value.split(' ')[0]} (${heigth}x${width} CM)`); $this.text(`${value.split(' ')[0]} (${heigth}x${width} CM)`);
} }
}); });
}, 1500); }, 1500);
} }
}); });
</script> </script>
<?php } ?>
<?php }
<?php
} }
$show_custom_tab = $_config->getProductDetail('show_custom_tab'); $show_custom_tab = $_config->getProductDetail('show_custom_tab');
$custom_tab_name = $_config->getProductDetail('custom_tab_name'); $custom_tab_name = $_config->getProductDetail('custom_tab_name');
$customtab_content = $_config->getProductDetail('customtab_content'); $customtab_content = $_config->getProductDetail('customtab_content');
?> ?>
<?php if(!empty($product->getCustomAttribute('tile_price'))){?>
<link rel="stylesheet" type="text/css" media="all" href="//localhost/coconva2118/pub/static/version1569245418/frontend/Sm/shop4u/en_US/js/jquery.selectareas.css">
<script type="text/javascript">
var tile_desc='<?php echo $product->getCustomAttribute('tile_price')->getValue();?>';
tile_desc = tile_desc.split('-');
var tile_width = parseInt(tile_desc[0]);
var tile_height = parseInt(tile_desc[1]);
var tile_price = parseInt(tile_desc[2]);
</script>
<style type="text/css">
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #eeeeee;
border-bottom: 16px solid #eeeeee;
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
position: absolute;
z-index: 99999;
left: 50%;
transform: translate(-50%,-50%);
top: 50%;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loader-wrapper{
position: fixed;
height: 100%;
width: 100%;
background: rgba(0,0,0,0.4);
z-index: 999;
top: 0;
left: 0;
}
.flip {
transform: rotateY(180deg);
}
</style>
<script>
var DefVal = 350;
var widthLabel = 'Width For Wall Mural';
var heightLabel = 'Height For Wall Mural';
var positionLabel = 'Image Position';
//jQuery('span:contains("Image Width")').parent().next('div').children('input').val();
require([
'jquery',
'selectareas'
//'//localhost/coconva2118/pub/static/version1569245418/frontend/Sm/shop4u/en_US/js/jquery.selectareas.js'
], function (jQuery, selectareas) {
jQuery('.price-final_price').html(' ');
jQuery.noConflict();
if (jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').length && jQuery('span:contains('+heightLabel+')').parent().next('div').children('input').length) {
//jQuery('body').loader('show');
jQuery('label:contains("Flip Image")').first().hide();
jQuery(".col2-layout .container .row ").append('<div id="preloader" class="loader-wrapper"><div class="loader"></div></div>');
function debugQtyAreas (event, id, areas) {
jQuery.each(areas, function (id, area) {
console.log('area====',area);
jQuery('span:contains('+positionLabel+')').parent().next('div').children('input').val('Xpos:'+(area.x).toFixed(2)+' :: Ypos:'+(area.y).toFixed(2));
});
};
function setPrice(p_w,p_h,t_w,t_h,rate,plugin){
var final_price = ((Math.ceil(p_w/t_w)*Math.ceil(p_h/t_h))*rate) + plugin;
jQuery('.price-final_price').html('<div id="prodPrice" style="font-size: 166.67%;color: #e74c3c;">₹'+final_price+'.00 </div>');
}
//----------------------creating checkbox for tiles------------//
jQuery(
'<div style="height: 30px;width: 100%;position: unset;padding-bottom: 35px;"><input type="checkbox" id="tile_checkbox">&nbsp;Show Tiles</div>'
).insertBefore('.product-add-form');
jQuery('label:contains("Flip Image")').first().next('div.control').children('div:nth-child(1)').children().children('input').on('change',function(){
if(jQuery(this).is(':checked')){
jQuery('img.fotorama__img').parent().addClass('flip');
}else{
jQuery('img.fotorama__img').parent().removeClass('flip');
}
});
//-------------------------------------------------------------//
setTimeout(function(){
var f_tile_width = (typeof tile_width !== 'undefined')?tile_width:50;
var f_tile_height = (typeof tile_height !== 'undefined')?tile_height:50;
var f_tile_price = (typeof tile_price !== 'undefined')?tile_price:50;
jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val(DefVal);
jQuery('span:contains('+heightLabel+')').parent().next('div').children('input').val(DefVal);
jQuery('span:contains('+positionLabel+')').parent().next('div').children('input').attr('disabled','disabled');
if(jQuery('.gallery-placeholder').html('<div><img src="'+ jQuery('img.fotorama__img').attr('src') +'" class="fotorama__img"/></div>')){
var tt = jQuery('img.fotorama__img').selectAreas({
// minSize: [500, 500],
onChanged: debugQtyAreas,
width: DefVal,
height: DefVal,
maxAreas: 1,
areas: [
{
x: 0,
y: 0,
width: DefVal,
height: DefVal,
}
]
});
setPrice(DefVal,DefVal,f_tile_width,f_tile_height,f_tile_price,0);
}
function setChangeArea(){
var w = jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val();
var h = jQuery('span:contains('+heightLabel+')').parent().next('div').children('input').val();
var xpos=0; var ypos=0;
if(parseInt(w) < 100 || parseInt(h) < 100){
alert("Minimum Value for Height and Width should be 100.");
return false;
}
if(parseInt(w) > parseInt(h)){ console.log('come in wid greater');
h = DefVal * (h/w);
w = DefVal;
ypos = (DefVal - h)/2;
}else if(parseInt(h) > parseInt(w)){
w = DefVal * (w/h);
h = DefVal;
xpos = (DefVal - w)/2;
}else{
w = DefVal;
h = DefVal;
}
console.log('h=',h,', w=',w,', xpos=',xpos,', ypos=',ypos);
var areaOptions = {
x: xpos,
y: ypos,
width: w,
height: h,
};
tt.selectAreas('reset');
jQuery('img.fotorama__img').selectAreas('add', areaOptions);
jQuery('.select-areas-resize-handler').remove();
jQuery('.delete-area').remove();
jQuery('#tile_checkbox').prop('checked', false);
setPrice(jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val(),jQuery('span:contains('+heightLabel+')').parent().next('div').children('input').val(),f_tile_width,f_tile_height,f_tile_price,0);
jQuery('.admin__control-radio').each(function(){jQuery(this).prop('checked', false)});
};
//--------------------------hiding price span--------------------//
jQuery('.price-notice').hide();
jQuery('.price-container.tax.weee').hide();
jQuery('.fotorama__img').parent().css('left','34px');
jQuery('.fotorama__img').parent().css('top','25px');
//------------------------- hiding price span--------------------//
//----------------------appending price update on material options----------//
jQuery('.admin__control-radio').each(function(){jQuery(this).change(
function(){
console.log('price==',jQuery(this).attr('price'));
setPrice(jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val(),jQuery('span:contains('+heightLabel+')').parent().next('div').children('input').val(),f_tile_width,f_tile_height,f_tile_price,parseInt(jQuery(this).attr('price')));
});
});
//--------------------------------------------------------------------------//
setTimeout(function(){
jQuery(jQuery('span:contains('+widthLabel+')').parent().next('div').children('input')).change(function(){setChangeArea();});
jQuery(jQuery('span:contains('+heightLabel+')').parent().next('div').children('input')).change(function(){setChangeArea();});
jQuery('.select-areas-resize-handler').remove();
jQuery('.delete-area').remove();
//------------------creating tiles here---------------------------//
jQuery('#tile_checkbox').on('change',function(){
if(jQuery(this).is(':checked')){
var htm = '<div style="background:white;color:white;"><ul>';
var kk=0;
var wh = jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val();
var hh = jQuery('span:contains('+heightLabel+')').parent().next('div').children('input').val();
var wdc = DefVal;
if(parseInt(wh) > parseInt(hh)){
wdc = DefVal;
}else if(parseInt(hh) > parseInt(wh)){
wdc = DefVal * (wh/hh);
}
for(i=0; i < parseInt(jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val()); i +=f_tile_width){
var wd = f_tile_width;
if((parseInt(jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val()) - i) < f_tile_width){
wd = parseInt(jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val()) - i;
}
var wdPer = (wd/parseInt(jQuery('span:contains('+widthLabel+')').parent().next('div').children('input').val()))*100;
htm += '<li style="left:'+kk+'px;width:'+Math.round((wdPer/100)*wdc)+'px;height:100%;position:absolute;background:grey;opacity:0.5;border:solid 1px"><div style="box-sizing:border-box;position:relative;height:100%;padding-top:5px;font-size:13px;text-align:center"><span style="transform:translateX(-50%) translateY(-50%) rotate(90deg);display:block;text-align:center;position:absolute;padding-left:'+(hh/10)*4+'px;padding-bottom:90%;">'+Math.round((wdPer/100)*wh)+'cm</span></div></li>';
kk +=Math.round((wdPer/100)*wdc);
}
htm += '</ul></div>';
jQuery('.select-areas-background-area').html(htm);
}else{
jQuery('.select-areas-background-area').html(' ');
}
});
//----------------------------------------------------------------//
},1000);
jQuery('#preloader').remove();
}, 2000);
}
});
</script>
<?php } ?>
<?php if ($detailedInfoGroup = $block->getGroupChildNames('detailed_info', 'getChildHtml')): ?> <?php if ($detailedInfoGroup = $block->getGroupChildNames('detailed_info', 'getChildHtml')): ?>
<div class="product info detailed"> <div class="product info detailed">
<?php $layout = $block->getLayout(); ?> <?php $layout = $block->getLayout(); ?>
......
...@@ -16,9 +16,8 @@ $_config = $this->helper('Sm\Shop4u\Helper\Data'); ...@@ -16,9 +16,8 @@ $_config = $this->helper('Sm\Shop4u\Helper\Data');
$zoom_enable = $_config->getProductDetail('use_zoom_image'); $zoom_enable = $_config->getProductDetail('use_zoom_image');
$zoom_width = $_config->getProductDetail('zoom_width'); $zoom_width = $_config->getProductDetail('zoom_width');
$thumbstyle = "vertical";
//$thumbstyle = $_config->getProductDetail('thumbs_style'); //$thumbstyle = $_config->getProductDetail('thumbs_style');
$thumbstyle = 'vertical';
$loop = $_config->getProductDetail('image_loop'); $loop = $_config->getProductDetail('image_loop');
$keyboard = $_config->getProductDetail('image_keyboard'); $keyboard = $_config->getProductDetail('image_keyboard');
$bigNav = $_config->getProductDetail('image_navigation'); $bigNav = $_config->getProductDetail('image_navigation');
...@@ -29,9 +28,8 @@ $thumbs_nav = $_config->getProductDetail('thumbs_navigation'); ...@@ -29,9 +28,8 @@ $thumbs_nav = $_config->getProductDetail('thumbs_navigation');
$breakpoints = $_config->getProductDetail('breakpoints_width'); $breakpoints = $_config->getProductDetail('breakpoints_width');
?>
?>
...@@ -70,6 +68,8 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) { ...@@ -70,6 +68,8 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) {
], function ($) { ], function ($) {
'use strict'; 'use strict';
setTimeout(function () { setTimeout(function () {
jQuery('span:contains("Canvas Images")').parent().next().children().attr('readonly','readonly');
jQuery('.image-upload-custom<?php echo $optionKey; ?>').click(function () { jQuery('.image-upload-custom<?php echo $optionKey; ?>').click(function () {
jQuery('#imgupload<?php echo $optionKey; ?>').trigger('click'); jQuery('#imgupload<?php echo $optionKey; ?>').trigger('click');
}); });
...@@ -82,6 +82,7 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) { ...@@ -82,6 +82,7 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) {
}, 1500); }, 1500);
}); });
function imageHolder<?php echo $optionKey; ?>(status, message, imageUrl) { function imageHolder<?php echo $optionKey; ?>(status, message, imageUrl) {
if (status) { if (status) {
require([ require([
...@@ -90,6 +91,12 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) { ...@@ -90,6 +91,12 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) {
if (jQuery('#imgupload<?php echo $optionKey; ?>').length) { if (jQuery('#imgupload<?php echo $optionKey; ?>').length) {
jQuery('.image-upload-custom<?php echo $optionKey; ?>').html(""); jQuery('.image-upload-custom<?php echo $optionKey; ?>').html("");
jQuery('.image-upload-custom<?php echo $optionKey; ?>').append("<img src='" + imageUrl + "' style='width:1000%; height:100%'>"); jQuery('.image-upload-custom<?php echo $optionKey; ?>').append("<img src='" + imageUrl + "' style='width:1000%; height:100%'>");
var imgSpl = imageUrl.split('/');
jQuery('span:contains("Canvas Images")').parent().next().children().val((jQuery('span:contains("Canvas Images")').parent().next().children().val()+','+imgSpl[imgSpl.length - 1]).replace(/^,|,$/g,''));
jQuery('span:contains("Canvas Images")').parent().next().children().attr('readonly','readonly');
} }
}); });
} }
...@@ -105,6 +112,60 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) { ...@@ -105,6 +112,60 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) {
<?php /*
<div style="width: 120px;height: 300px;position: absolute;border: 2px solid red;z-index: 99999;margin: auto;margin-left: 106px;">
<form action="/shop4u/index/index" method="post" target="my_iframe" enctype="multipart/form-data">
<input type="file" name="file" id="imgupload" style="display:none"/>
<div class='image-upload-custom' style="width: 120px;height: 300px;border: 3px solid gray;"></div>
</form>
<iframe name="my_iframe" src="" style="display: none"></iframe>
<script>
require([
'jquery',
], function ($) {
'use strict';
setTimeout(function () {
jQuery('.image-upload-custom').click(function () {
jQuery('#imgupload').trigger('click');
});
jQuery('#imgupload').change(function() {
if (jQuery(this).val() != '') {
jQuery(this).parents('form').submit();
}
});
}, 1500);
});
function imageHolder(status, message, imageUrl) {
if (status) {
require([
'jquery',
], function ($) {
if (jQuery('#imgupload').length) {
jQuery('.image-upload-custom').append("<img src='" + imageUrl + "' style='width:1000%; height:100%'>");
}
});
}
}
</script>
</div>
*/ ?>
<div class="gallery-placeholder _block-content-loading" data-gallery-role="gallery-placeholder"> <div class="gallery-placeholder _block-content-loading" data-gallery-role="gallery-placeholder">
<div data-role="loader" class="loading-mask"> <div data-role="loader" class="loading-mask">
<div class="loader"> <div class="loader">
...@@ -137,7 +198,7 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) { ...@@ -137,7 +198,7 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) {
{ {
"[data-gallery-role=gallery-placeholder]": { "[data-gallery-role=gallery-placeholder]": {
"mage/gallery/gallery": { "mage/gallery/gallery": {
"mixins":["magnifier/magnify"], <?php /* ?> "mixins":["magnifier/magnify"],
"magnifierOpts": { "magnifierOpts": {
<?php if ($zoom_enable) { ?> <?php if ($zoom_enable) { ?>
"enabled": true, "enabled": true,
...@@ -154,7 +215,8 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) { ...@@ -154,7 +215,8 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) {
"width": <?php echo $zoom_width; ?>, "width": <?php echo $zoom_width; ?>,
"mode": "outside" "mode": "outside"
}, },
"data": <?php /* @escapeNotVerified */ <?php */ ?>
"data": <?php /* @escapeNotVerified */
echo $block->getGalleryImagesJson(); ?>, echo $block->getGalleryImagesJson(); ?>,
"options": { "options": {
<?php if ($thumbstyle == 'horizontal' || $thumbstyle == 'vertical') { ?> <?php if ($thumbstyle == 'horizontal' || $thumbstyle == 'vertical') { ?>
...@@ -282,3 +344,4 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) { ...@@ -282,3 +344,4 @@ if (!empty($product->getCustomAttribute('image_canvas_area'))) {
} }
</script> </script>
/*************************
* Croppie
* Copyright 2019
* Foliotek
* Version: 2.6.4
*************************/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
module.exports = factory();
} else {
// Browser globals
root.Croppie = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
/* Polyfills */
if (typeof Promise !== 'function') {
/*! promise-polyfill 3.1.0 */
!function(a){function b(a,b){return function(){a.apply(b,arguments)}}function c(a){if("object"!==typeof this)throw new TypeError("Promises must be constructed via new");if("function"!==typeof a)throw new TypeError("not a function");this._state=null,this._value=null,this._deferreds=[],i(a,b(e,this),b(f,this))}function d(a){var b=this;return null===this._state?void this._deferreds.push(a):void k(function(){var c=b._state?a.onFulfilled:a.onRejected;if(null===c)return void(b._state?a.resolve:a.reject)(b._value);var d;try{d=c(b._value)}catch(e){return void a.reject(e)}a.resolve(d)})}function e(a){try{if(a===this)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"===typeof a||"function"===typeof a)){var c=a.then;if("function"===typeof c)return void i(b(c,a),b(e,this),b(f,this))}this._state=!0,this._value=a,g.call(this)}catch(d){f.call(this,d)}}function f(a){this._state=!1,this._value=a,g.call(this)}function g(){for(var a=0,b=this._deferreds.length;b>a;a++)d.call(this,this._deferreds[a]);this._deferreds=null}function h(a,b,c,d){this.onFulfilled="function"===typeof a?a:null,this.onRejected="function"===typeof b?b:null,this.resolve=c,this.reject=d}function i(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var j=setTimeout,k="function"===typeof setImmediate&&setImmediate||function(a){j(a,1)},l=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)};c.prototype["catch"]=function(a){return this.then(null,a)},c.prototype.then=function(a,b){var e=this;return new c(function(c,f){d.call(e,new h(a,b,c,f))})},c.all=function(){var a=Array.prototype.slice.call(1===arguments.length&&l(arguments[0])?arguments[0]:arguments);return new c(function(b,c){function d(f,g){try{if(g&&("object"===typeof g||"function"===typeof g)){var h=g.then;if("function"===typeof h)return void h.call(g,function(a){d(f,a)},c)}a[f]=g,0===--e&&b(a)}catch(i){c(i)}}if(0===a.length)return b([]);for(var e=a.length,f=0;f<a.length;f++)d(f,a[f])})},c.resolve=function(a){return a&&"object"===typeof a&&a.constructor===c?a:new c(function(b){b(a)})},c.reject=function(a){return new c(function(b,c){c(a)})},c.race=function(a){return new c(function(b,c){for(var d=0,e=a.length;e>d;d++)a[d].then(b,c)})},c._setImmediateFn=function(a){k=a},"undefined"!==typeof module&&module.exports?module.exports=c:a.Promise||(a.Promise=c)}(this);
}
if ( typeof window.CustomEvent !== "function" ) {
(function(){
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
}());
}
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
len = binStr.length,
arr = new Uint8Array(len);
for (var i=0; i<len; i++ ) {
arr[i] = binStr.charCodeAt(i);
}
callback( new Blob( [arr], {type: type || 'image/png'} ) );
}
});
}
/* End Polyfills */
var cssPrefixes = ['Webkit', 'Moz', 'ms'],
emptyStyles = document.createElement('div').style,
EXIF_NORM = [1,8,3,6],
EXIF_FLIP = [2,7,4,5],
CSS_TRANS_ORG,
CSS_TRANSFORM,
CSS_USERSELECT;
function vendorPrefix(prop) {
if (prop in emptyStyles) {
return prop;
}
var capProp = prop[0].toUpperCase() + prop.slice(1),
i = cssPrefixes.length;
while (i--) {
prop = cssPrefixes[i] + capProp;
if (prop in emptyStyles) {
return prop;
}
}
}
CSS_TRANSFORM = vendorPrefix('transform');
CSS_TRANS_ORG = vendorPrefix('transformOrigin');
CSS_USERSELECT = vendorPrefix('userSelect');
function getExifOffset(ornt, rotate) {
var arr = EXIF_NORM.indexOf(ornt) > -1 ? EXIF_NORM : EXIF_FLIP,
index = arr.indexOf(ornt),
offset = (rotate / 90) % arr.length;// 180 = 2%4 = 2 shift exif by 2 indexes
return arr[(arr.length + index + (offset % arr.length)) % arr.length];
}
// Credits to : Andrew Dupont - http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/
function deepExtend(destination, source) {
destination = destination || {};
for (var property in source) {
if (source[property] && source[property].constructor && source[property].constructor === Object) {
destination[property] = destination[property] || {};
deepExtend(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
}
function clone(object) {
return deepExtend({}, object);
}
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function dispatchChange(element) {
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else {
element.fireEvent("onchange");
}
}
//http://jsperf.com/vanilla-css
function css(el, styles, val) {
if (typeof (styles) === 'string') {
var tmp = styles;
styles = {};
styles[tmp] = val;
}
for (var prop in styles) {
el.style[prop] = styles[prop];
}
}
function addClass(el, c) {
if (el.classList) {
el.classList.add(c);
}
else {
el.className += ' ' + c;
}
}
function removeClass(el, c) {
if (el.classList) {
el.classList.remove(c);
}
else {
el.className = el.className.replace(c, '');
}
}
function setAttributes(el, attrs) {
for (var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
function num(v) {
return parseInt(v, 10);
}
/* Utilities */
function loadImage(src, doExif) {
var img = new Image();
img.style.opacity = '0';
return new Promise(function (resolve, reject) {
function _resolve() {
img.style.opacity = '1';
setTimeout(function () {
resolve(img);
}, 1);
}
img.removeAttribute('crossOrigin');
if (src.match(/^https?:\/\/|^\/\//)) {
img.setAttribute('crossOrigin', 'anonymous');
}
img.onload = function () {
if (doExif) {
EXIF.getData(img, function () {
_resolve();
});
}
else {
_resolve();
}
};
img.onerror = function (ev) {
img.style.opacity = 1;
setTimeout(function () {
reject(ev);
}, 1);
};
img.src = src;
});
}
function naturalImageDimensions(img, ornt) {
var w = img.naturalWidth;
var h = img.naturalHeight;
var orient = ornt || getExifOrientation(img);
if (orient && orient >= 5) {
var x= w;
w = h;
h = x;
}
return { width: w, height: h };
}
/* CSS Transform Prototype */
var TRANSLATE_OPTS = {
'translate3d': {
suffix: ', 0px'
},
'translate': {
suffix: ''
}
};
var Transform = function (x, y, scale) {
this.x = parseFloat(x);
this.y = parseFloat(y);
this.scale = parseFloat(scale);
};
Transform.parse = function (v) {
if (v.style) {
return Transform.parse(v.style[CSS_TRANSFORM]);
}
else if (v.indexOf('matrix') > -1 || v.indexOf('none') > -1) {
return Transform.fromMatrix(v);
}
else {
return Transform.fromString(v);
}
};
Transform.fromMatrix = function (v) {
var vals = v.substring(7).split(',');
if (!vals.length || v === 'none') {
vals = [1, 0, 0, 1, 0, 0];
}
return new Transform(num(vals[4]), num(vals[5]), parseFloat(vals[0]));
};
Transform.fromString = function (v) {
var values = v.split(') '),
translate = values[0].substring(Croppie.globals.translate.length + 1).split(','),
scale = values.length > 1 ? values[1].substring(6) : 1,
x = translate.length > 1 ? translate[0] : 0,
y = translate.length > 1 ? translate[1] : 0;
return new Transform(x, y, scale);
};
Transform.prototype.toString = function () {
var suffix = TRANSLATE_OPTS[Croppie.globals.translate].suffix || '';
return Croppie.globals.translate + '(' + this.x + 'px, ' + this.y + 'px' + suffix + ') scale(' + this.scale + ')';
};
var TransformOrigin = function (el) {
if (!el || !el.style[CSS_TRANS_ORG]) {
this.x = 0;
this.y = 0;
return;
}
var css = el.style[CSS_TRANS_ORG].split(' ');
this.x = parseFloat(css[0]);
this.y = parseFloat(css[1]);
};
TransformOrigin.prototype.toString = function () {
return this.x + 'px ' + this.y + 'px';
};
function getExifOrientation (img) {
return img.exifdata && img.exifdata.Orientation ? num(img.exifdata.Orientation) : 1;
}
function drawCanvas(canvas, img, orientation) {
var width = img.width,
height = img.height,
ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.save();
switch (orientation) {
case 2:
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
ctx.translate(width, height);
ctx.rotate(180*Math.PI/180);
break;
case 4:
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
canvas.width = height;
canvas.height = width;
ctx.rotate(90*Math.PI/180);
ctx.scale(1, -1);
break;
case 6:
canvas.width = height;
canvas.height = width;
ctx.rotate(90*Math.PI/180);
ctx.translate(0, -height);
break;
case 7:
canvas.width = height;
canvas.height = width;
ctx.rotate(-90*Math.PI/180);
ctx.translate(-width, height);
ctx.scale(1, -1);
break;
case 8:
canvas.width = height;
canvas.height = width;
ctx.translate(0, width);
ctx.rotate(-90*Math.PI/180);
break;
}
ctx.drawImage(img, 0,0, width, height);
ctx.restore();
}
/* Private Methods */
function _create() {
var self = this,
contClass = 'croppie-container',
customViewportClass = self.options.viewport.type ? 'cr-vp-' + self.options.viewport.type : null,
boundary, img, viewport, overlay, bw, bh;
self.options.useCanvas = self.options.enableOrientation || _hasExif.call(self);
// Properties on class
self.data = {};
self.elements = {};
boundary = self.elements.boundary = document.createElement('div');
viewport = self.elements.viewport = document.createElement('div');
img = self.elements.img = document.createElement('img');
overlay = self.elements.overlay = document.createElement('div');
if (self.options.useCanvas) {
self.elements.canvas = document.createElement('canvas');
self.elements.preview = self.elements.canvas;
}
else {
self.elements.preview = img;
}
addClass(boundary, 'cr-boundary');
boundary.setAttribute('aria-dropeffect', 'none');
bw = self.options.boundary.width;
bh = self.options.boundary.height;
css(boundary, {
width: (bw + (isNaN(bw) ? '' : 'px')),
height: (bh + (isNaN(bh) ? '' : 'px'))
});
addClass(viewport, 'cr-viewport');
if (customViewportClass) {
addClass(viewport, customViewportClass);
}
css(viewport, {
width: self.options.viewport.width + 'px',
height: self.options.viewport.height + 'px'
});
viewport.setAttribute('tabindex', 0);
addClass(self.elements.preview, 'cr-image');
setAttributes(self.elements.preview, { 'alt': 'preview', 'aria-grabbed': 'false' });
addClass(overlay, 'cr-overlay');
self.element.appendChild(boundary);
boundary.appendChild(self.elements.preview);
boundary.appendChild(viewport);
boundary.appendChild(overlay);
addClass(self.element, contClass);
if (self.options.customClass) {
addClass(self.element, self.options.customClass);
}
_initDraggable.call(this);
if (self.options.enableZoom) {
_initializeZoom.call(self);
}
// if (self.options.enableOrientation) {
// _initRotationControls.call(self);
// }
if (self.options.enableResize) {
_initializeResize.call(self);
}
}
// function _initRotationControls () {
// var self = this,
// wrap, btnLeft, btnRight, iLeft, iRight;
// wrap = document.createElement('div');
// self.elements.orientationBtnLeft = btnLeft = document.createElement('button');
// self.elements.orientationBtnRight = btnRight = document.createElement('button');
// wrap.appendChild(btnLeft);
// wrap.appendChild(btnRight);
// iLeft = document.createElement('i');
// iRight = document.createElement('i');
// btnLeft.appendChild(iLeft);
// btnRight.appendChild(iRight);
// addClass(wrap, 'cr-rotate-controls');
// addClass(btnLeft, 'cr-rotate-l');
// addClass(btnRight, 'cr-rotate-r');
// self.elements.boundary.appendChild(wrap);
// btnLeft.addEventListener('click', function () {
// self.rotate(-90);
// });
// btnRight.addEventListener('click', function () {
// self.rotate(90);
// });
// }
function _hasExif() {
return this.options.enableExif && window.EXIF;
}
function _initializeResize () {
var self = this;
var wrap = document.createElement('div');
var isDragging = false;
var direction;
var originalX;
var originalY;
var minSize = 50;
var maxWidth;
var maxHeight;
var vr;
var hr;
addClass(wrap, 'cr-resizer');
css(wrap, {
width: this.options.viewport.width + 'px',
height: this.options.viewport.height + 'px'
});
if (this.options.resizeControls.height) {
vr = document.createElement('div');
addClass(vr, 'cr-resizer-vertical');
wrap.appendChild(vr);
}
if (this.options.resizeControls.width) {
hr = document.createElement('div');
addClass(hr, 'cr-resizer-horisontal');
wrap.appendChild(hr);
}
function mouseDown(ev) {
if (ev.button !== undefined && ev.button !== 0) return;
ev.preventDefault();
if (isDragging) {
return;
}
var overlayRect = self.elements.overlay.getBoundingClientRect();
isDragging = true;
originalX = ev.pageX;
originalY = ev.pageY;
direction = ev.currentTarget.className.indexOf('vertical') !== -1 ? 'v' : 'h';
maxWidth = overlayRect.width;
maxHeight = overlayRect.height;
if (ev.touches) {
var touches = ev.touches[0];
originalX = touches.pageX;
originalY = touches.pageY;
}
window.addEventListener('mousemove', mouseMove);
window.addEventListener('touchmove', mouseMove);
window.addEventListener('mouseup', mouseUp);
window.addEventListener('touchend', mouseUp);
document.body.style[CSS_USERSELECT] = 'none';
}
function mouseMove(ev) {
var pageX = ev.pageX;
var pageY = ev.pageY;
ev.preventDefault();
if (ev.touches) {
var touches = ev.touches[0];
pageX = touches.pageX;
pageY = touches.pageY;
}
var deltaX = pageX - originalX;
var deltaY = pageY - originalY;
var newHeight = self.options.viewport.height + deltaY;
var newWidth = self.options.viewport.width + deltaX;
if (direction === 'v' && newHeight >= minSize && newHeight <= maxHeight) {
css(wrap, {
height: newHeight + 'px'
});
self.options.boundary.height += deltaY;
css(self.elements.boundary, {
height: self.options.boundary.height + 'px'
});
self.options.viewport.height += deltaY;
css(self.elements.viewport, {
height: self.options.viewport.height + 'px'
});
}
else if (direction === 'h' && newWidth >= minSize && newWidth <= maxWidth) {
css(wrap, {
width: newWidth + 'px'
});
self.options.boundary.width += deltaX;
css(self.elements.boundary, {
width: self.options.boundary.width + 'px'
});
self.options.viewport.width += deltaX;
css(self.elements.viewport, {
width: self.options.viewport.width + 'px'
});
}
_updateOverlay.call(self);
_updateZoomLimits.call(self);
_updateCenterPoint.call(self);
_triggerUpdate.call(self);
originalY = pageY;
originalX = pageX;
}
function mouseUp() {
isDragging = false;
window.removeEventListener('mousemove', mouseMove);
window.removeEventListener('touchmove', mouseMove);
window.removeEventListener('mouseup', mouseUp);
window.removeEventListener('touchend', mouseUp);
document.body.style[CSS_USERSELECT] = '';
}
if (vr) {
vr.addEventListener('mousedown', mouseDown);
vr.addEventListener('touchstart', mouseDown);
}
if (hr) {
hr.addEventListener('mousedown', mouseDown);
hr.addEventListener('touchstart', mouseDown);
}
this.elements.boundary.appendChild(wrap);
}
function _setZoomerVal(v) {
if (this.options.enableZoom) {
var z = this.elements.zoomer,
val = fix(v, 4);
z.value = Math.max(parseFloat(z.min), Math.min(parseFloat(z.max), val)).toString();
}
}
function _initializeZoom() {
var self = this,
wrap = self.elements.zoomerWrap = document.createElement('div'),
zoomer = self.elements.zoomer = document.createElement('input');
addClass(wrap, 'cr-slider-wrap');
addClass(zoomer, 'cr-slider');
zoomer.type = 'range';
zoomer.step = '0.0001';
zoomer.value = '1';
zoomer.style.display = self.options.showZoomer ? '' : 'none';
zoomer.setAttribute('aria-label', 'zoom');
self.element.appendChild(wrap);
wrap.appendChild(zoomer);
self._currentZoom = 1;
function change() {
_onZoom.call(self, {
value: parseFloat(zoomer.value),
origin: new TransformOrigin(self.elements.preview),
viewportRect: self.elements.viewport.getBoundingClientRect(),
transform: Transform.parse(self.elements.preview)
});
}
function scroll(ev) {
var delta, targetZoom;
if(self.options.mouseWheelZoom === 'ctrl' && ev.ctrlKey !== true){
return 0;
} else if (ev.wheelDelta) {
delta = ev.wheelDelta / 1200; //wheelDelta min: -120 max: 120 // max x 10 x 2
} else if (ev.deltaY) {
delta = ev.deltaY / 1060; //deltaY min: -53 max: 53 // max x 10 x 2
} else if (ev.detail) {
delta = ev.detail / -60; //delta min: -3 max: 3 // max x 10 x 2
} else {
delta = 0;
}
targetZoom = self._currentZoom + (delta * self._currentZoom);
ev.preventDefault();
_setZoomerVal.call(self, targetZoom);
change.call(self);
}
self.elements.zoomer.addEventListener('input', change);// this is being fired twice on keypress
self.elements.zoomer.addEventListener('change', change);
if (self.options.mouseWheelZoom) {
self.elements.boundary.addEventListener('mousewheel', scroll);
self.elements.boundary.addEventListener('DOMMouseScroll', scroll);
}
}
function _onZoom(ui) {
var self = this,
transform = ui ? ui.transform : Transform.parse(self.elements.preview),
vpRect = ui ? ui.viewportRect : self.elements.viewport.getBoundingClientRect(),
origin = ui ? ui.origin : new TransformOrigin(self.elements.preview);
function applyCss() {
var transCss = {};
transCss[CSS_TRANSFORM] = transform.toString();
transCss[CSS_TRANS_ORG] = origin.toString();
css(self.elements.preview, transCss);
}
self._currentZoom = ui ? ui.value : self._currentZoom;
transform.scale = self._currentZoom;
self.elements.zoomer.setAttribute('aria-valuenow', self._currentZoom);
applyCss();
if (self.options.enforceBoundary) {
var boundaries = _getVirtualBoundaries.call(self, vpRect),
transBoundaries = boundaries.translate,
oBoundaries = boundaries.origin;
if (transform.x >= transBoundaries.maxX) {
origin.x = oBoundaries.minX;
transform.x = transBoundaries.maxX;
}
if (transform.x <= transBoundaries.minX) {
origin.x = oBoundaries.maxX;
transform.x = transBoundaries.minX;
}
if (transform.y >= transBoundaries.maxY) {
origin.y = oBoundaries.minY;
transform.y = transBoundaries.maxY;
}
if (transform.y <= transBoundaries.minY) {
origin.y = oBoundaries.maxY;
transform.y = transBoundaries.minY;
}
}
applyCss();
_debouncedOverlay.call(self);
_triggerUpdate.call(self);
}
function _getVirtualBoundaries(viewport) {
var self = this,
scale = self._currentZoom,
vpWidth = viewport.width,
vpHeight = viewport.height,
centerFromBoundaryX = self.elements.boundary.clientWidth / 2,
centerFromBoundaryY = self.elements.boundary.clientHeight / 2,
imgRect = self.elements.preview.getBoundingClientRect(),
curImgWidth = imgRect.width,
curImgHeight = imgRect.height,
halfWidth = vpWidth / 2,
halfHeight = vpHeight / 2;
var maxX = ((halfWidth / scale) - centerFromBoundaryX) * -1;
var minX = maxX - ((curImgWidth * (1 / scale)) - (vpWidth * (1 / scale)));
var maxY = ((halfHeight / scale) - centerFromBoundaryY) * -1;
var minY = maxY - ((curImgHeight * (1 / scale)) - (vpHeight * (1 / scale)));
var originMinX = (1 / scale) * halfWidth;
var originMaxX = (curImgWidth * (1 / scale)) - originMinX;
var originMinY = (1 / scale) * halfHeight;
var originMaxY = (curImgHeight * (1 / scale)) - originMinY;
return {
translate: {
maxX: maxX,
minX: minX,
maxY: maxY,
minY: minY
},
origin: {
maxX: originMaxX,
minX: originMinX,
maxY: originMaxY,
minY: originMinY
}
};
}
function _updateCenterPoint(rotate) {
var self = this,
scale = self._currentZoom,
data = self.elements.preview.getBoundingClientRect(),
vpData = self.elements.viewport.getBoundingClientRect(),
transform = Transform.parse(self.elements.preview.style[CSS_TRANSFORM]),
pc = new TransformOrigin(self.elements.preview),
top = (vpData.top - data.top) + (vpData.height / 2),
left = (vpData.left - data.left) + (vpData.width / 2),
center = {},
adj = {};
if (rotate) {
var cx = pc.x;
var cy = pc.y;
var tx = transform.x;
var ty = transform.y;
center.y = cx;
center.x = cy;
transform.y = tx;
transform.x = ty;
}
else {
center.y = top / scale;
center.x = left / scale;
adj.y = (center.y - pc.y) * (1 - scale);
adj.x = (center.x - pc.x) * (1 - scale);
transform.x -= adj.x;
transform.y -= adj.y;
}
var newCss = {};
newCss[CSS_TRANS_ORG] = center.x + 'px ' + center.y + 'px';
newCss[CSS_TRANSFORM] = transform.toString();
css(self.elements.preview, newCss);
}
function _initDraggable() {
var self = this,
isDragging = false,
originalX,
originalY,
originalDistance,
vpRect,
transform;
function assignTransformCoordinates(deltaX, deltaY) {
var imgRect = self.elements.preview.getBoundingClientRect(),
top = transform.y + deltaY,
left = transform.x + deltaX;
if (self.options.enforceBoundary) {
if (vpRect.top > imgRect.top + deltaY && vpRect.bottom < imgRect.bottom + deltaY) {
transform.y = top;
}
if (vpRect.left > imgRect.left + deltaX && vpRect.right < imgRect.right + deltaX) {
transform.x = left;
}
}
else {
transform.y = top;
transform.x = left;
}
}
function toggleGrabState(isDragging) {
self.elements.preview.setAttribute('aria-grabbed', isDragging);
self.elements.boundary.setAttribute('aria-dropeffect', isDragging? 'move': 'none');
}
function keyDown(ev) {
var LEFT_ARROW = 37,
UP_ARROW = 38,
RIGHT_ARROW = 39,
DOWN_ARROW = 40;
if (ev.shiftKey && (ev.keyCode === UP_ARROW || ev.keyCode === DOWN_ARROW)) {
var zoom;
if (ev.keyCode === UP_ARROW) {
zoom = parseFloat(self.elements.zoomer.value) + parseFloat(self.elements.zoomer.step)
}
else {
zoom = parseFloat(self.elements.zoomer.value) - parseFloat(self.elements.zoomer.step)
}
self.setZoom(zoom);
}
else if (self.options.enableKeyMovement && (ev.keyCode >= 37 && ev.keyCode <= 40)) {
ev.preventDefault();
var movement = parseKeyDown(ev.keyCode);
transform = Transform.parse(self.elements.preview);
document.body.style[CSS_USERSELECT] = 'none';
vpRect = self.elements.viewport.getBoundingClientRect();
keyMove(movement);
}
function parseKeyDown(key) {
switch (key) {
case LEFT_ARROW:
return [1, 0];
case UP_ARROW:
return [0, 1];
case RIGHT_ARROW:
return [-1, 0];
case DOWN_ARROW:
return [0, -1];
}
}
}
function keyMove(movement) {
var deltaX = movement[0],
deltaY = movement[1],
newCss = {};
assignTransformCoordinates(deltaX, deltaY);
newCss[CSS_TRANSFORM] = transform.toString();
css(self.elements.preview, newCss);
_updateOverlay.call(self);
document.body.style[CSS_USERSELECT] = '';
_updateCenterPoint.call(self);
_triggerUpdate.call(self);
originalDistance = 0;
}
function mouseDown(ev) {
if (ev.button !== undefined && ev.button !== 0) return;
ev.preventDefault();
if (isDragging) return;
isDragging = true;
originalX = ev.pageX;
originalY = ev.pageY;
if (ev.touches) {
var touches = ev.touches[0];
originalX = touches.pageX;
originalY = touches.pageY;
}
toggleGrabState(isDragging);
transform = Transform.parse(self.elements.preview);
window.addEventListener('mousemove', mouseMove);
window.addEventListener('touchmove', mouseMove);
window.addEventListener('mouseup', mouseUp);
window.addEventListener('touchend', mouseUp);
document.body.style[CSS_USERSELECT] = 'none';
vpRect = self.elements.viewport.getBoundingClientRect();
}
function mouseMove(ev) {
ev.preventDefault();
var pageX = ev.pageX,
pageY = ev.pageY;
if (ev.touches) {
var touches = ev.touches[0];
pageX = touches.pageX;
pageY = touches.pageY;
}
var deltaX = pageX - originalX,
deltaY = pageY - originalY,
newCss = {};
if (ev.type === 'touchmove') {
if (ev.touches.length > 1) {
var touch1 = ev.touches[0];
var touch2 = ev.touches[1];
var dist = Math.sqrt((touch1.pageX - touch2.pageX) * (touch1.pageX - touch2.pageX) + (touch1.pageY - touch2.pageY) * (touch1.pageY - touch2.pageY));
if (!originalDistance) {
originalDistance = dist / self._currentZoom;
}
var scale = dist / originalDistance;
_setZoomerVal.call(self, scale);
dispatchChange(self.elements.zoomer);
return;
}
}
assignTransformCoordinates(deltaX, deltaY);
newCss[CSS_TRANSFORM] = transform.toString();
css(self.elements.preview, newCss);
_updateOverlay.call(self);
originalY = pageY;
originalX = pageX;
}
function mouseUp() {
isDragging = false;
toggleGrabState(isDragging);
window.removeEventListener('mousemove', mouseMove);
window.removeEventListener('touchmove', mouseMove);
window.removeEventListener('mouseup', mouseUp);
window.removeEventListener('touchend', mouseUp);
document.body.style[CSS_USERSELECT] = '';
_updateCenterPoint.call(self);
_triggerUpdate.call(self);
originalDistance = 0;
}
self.elements.overlay.addEventListener('mousedown', mouseDown);
self.elements.viewport.addEventListener('keydown', keyDown);
self.elements.overlay.addEventListener('touchstart', mouseDown);
}
function _updateOverlay() {
if (!this.elements) return; // since this is debounced, it can be fired after destroy
var self = this,
boundRect = self.elements.boundary.getBoundingClientRect(),
imgData = self.elements.preview.getBoundingClientRect();
css(self.elements.overlay, {
width: imgData.width + 'px',
height: imgData.height + 'px',
top: (imgData.top - boundRect.top) + 'px',
left: (imgData.left - boundRect.left) + 'px'
});
}
var _debouncedOverlay = debounce(_updateOverlay, 500);
function _triggerUpdate() {
var self = this,
data = self.get();
if (!_isVisible.call(self)) {
return;
}
self.options.update.call(self, data);
if (self.$ && typeof Prototype === 'undefined') {
self.$(self.element).trigger('update.croppie', data);
}
else {
var ev;
if (window.CustomEvent) {
ev = new CustomEvent('update', { detail: data });
} else {
ev = document.createEvent('CustomEvent');
ev.initCustomEvent('update', true, true, data);
}
self.element.dispatchEvent(ev);
}
}
function _isVisible() {
return this.elements.preview.offsetHeight > 0 && this.elements.preview.offsetWidth > 0;
}
function _updatePropertiesFromImage() {
var self = this,
initialZoom = 1,
cssReset = {},
img = self.elements.preview,
imgData,
transformReset = new Transform(0, 0, initialZoom),
originReset = new TransformOrigin(),
isVisible = _isVisible.call(self);
if (!isVisible || self.data.bound) {// if the croppie isn't visible or it doesn't need binding
return;
}
self.data.bound = true;
cssReset[CSS_TRANSFORM] = transformReset.toString();
cssReset[CSS_TRANS_ORG] = originReset.toString();
cssReset['opacity'] = 1;
css(img, cssReset);
imgData = self.elements.preview.getBoundingClientRect();
self._originalImageWidth = imgData.width;
self._originalImageHeight = imgData.height;
self.data.orientation = getExifOrientation(self.elements.img);
if (self.options.enableZoom) {
_updateZoomLimits.call(self, true);
}
else {
self._currentZoom = initialZoom;
}
transformReset.scale = self._currentZoom;
cssReset[CSS_TRANSFORM] = transformReset.toString();
css(img, cssReset);
if (self.data.points.length) {
_bindPoints.call(self, self.data.points);
}
else {
_centerImage.call(self);
}
_updateCenterPoint.call(self);
_updateOverlay.call(self);
}
function _updateZoomLimits (initial) {
var self = this,
minZoom = Math.max(self.options.minZoom, 0) || 0,
maxZoom = self.options.maxZoom || 1.5,
initialZoom,
defaultInitialZoom,
zoomer = self.elements.zoomer,
scale = parseFloat(zoomer.value),
boundaryData = self.elements.boundary.getBoundingClientRect(),
imgData = naturalImageDimensions(self.elements.img, self.data.orientation),
vpData = self.elements.viewport.getBoundingClientRect(),
minW,
minH;
if (self.options.enforceBoundary) {
minW = vpData.width / imgData.width;
minH = vpData.height / imgData.height;
minZoom = Math.max(minW, minH);
}
if (minZoom >= maxZoom) {
maxZoom = minZoom + 1;
}
zoomer.min = fix(minZoom, 4);
zoomer.max = fix(maxZoom, 4);
if (!initial && (scale < zoomer.min || scale > zoomer.max)) {
_setZoomerVal.call(self, scale < zoomer.min ? zoomer.min : zoomer.max);
}
else if (initial) {
defaultInitialZoom = Math.max((boundaryData.width / imgData.width), (boundaryData.height / imgData.height));
initialZoom = self.data.boundZoom !== null ? self.data.boundZoom : defaultInitialZoom;
_setZoomerVal.call(self, initialZoom);
}
dispatchChange(zoomer);
}
function _bindPoints(points) {
if (points.length !== 4) {
throw "Croppie - Invalid number of points supplied: " + points;
}
var self = this,
pointsWidth = points[2] - points[0],
// pointsHeight = points[3] - points[1],
vpData = self.elements.viewport.getBoundingClientRect(),
boundRect = self.elements.boundary.getBoundingClientRect(),
vpOffset = {
left: vpData.left - boundRect.left,
top: vpData.top - boundRect.top
},
scale = vpData.width / pointsWidth,
originTop = points[1],
originLeft = points[0],
transformTop = (-1 * points[1]) + vpOffset.top,
transformLeft = (-1 * points[0]) + vpOffset.left,
newCss = {};
newCss[CSS_TRANS_ORG] = originLeft + 'px ' + originTop + 'px';
newCss[CSS_TRANSFORM] = new Transform(transformLeft, transformTop, scale).toString();
css(self.elements.preview, newCss);
_setZoomerVal.call(self, scale);
self._currentZoom = scale;
}
function _centerImage() {
var self = this,
imgDim = self.elements.preview.getBoundingClientRect(),
vpDim = self.elements.viewport.getBoundingClientRect(),
boundDim = self.elements.boundary.getBoundingClientRect(),
vpLeft = vpDim.left - boundDim.left,
vpTop = vpDim.top - boundDim.top,
w = vpLeft - ((imgDim.width - vpDim.width) / 2),
h = vpTop - ((imgDim.height - vpDim.height) / 2),
transform = new Transform(w, h, self._currentZoom);
css(self.elements.preview, CSS_TRANSFORM, transform.toString());
}
function _transferImageToCanvas(customOrientation) {
var self = this,
canvas = self.elements.canvas,
img = self.elements.img,
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = img.width;
canvas.height = img.height;
var orientation = self.options.enableOrientation && customOrientation || getExifOrientation(img);
drawCanvas(canvas, img, orientation);
}
function _getCanvas(data) {
var self = this,
points = data.points,
left = num(points[0]),
top = num(points[1]),
right = num(points[2]),
bottom = num(points[3]),
width = right-left,
height = bottom-top,
circle = data.circle,
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
startX = 0,
startY = 0,
canvasWidth = data.outputWidth || width,
canvasHeight = data.outputHeight || height;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
if (data.backgroundColor) {
ctx.fillStyle = data.backgroundColor;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
}
// By default assume we're going to draw the entire
// source image onto the destination canvas.
var sx = left,
sy = top,
sWidth = width,
sHeight = height,
dx = 0,
dy = 0,
dWidth = canvasWidth,
dHeight = canvasHeight;
//
// Do not go outside of the original image's bounds along the x-axis.
// Handle translations when projecting onto the destination canvas.
//
// The smallest possible source x-position is 0.
if (left < 0) {
sx = 0;
dx = (Math.abs(left) / width) * canvasWidth;
}
// The largest possible source width is the original image's width.
if (sWidth + sx > self._originalImageWidth) {
sWidth = self._originalImageWidth - sx;
dWidth = (sWidth / width) * canvasWidth;
}
//
// Do not go outside of the original image's bounds along the y-axis.
//
// The smallest possible source y-position is 0.
if (top < 0) {
sy = 0;
dy = (Math.abs(top) / height) * canvasHeight;
}
// The largest possible source height is the original image's height.
if (sHeight + sy > self._originalImageHeight) {
sHeight = self._originalImageHeight - sy;
dHeight = (sHeight / height) * canvasHeight;
}
// console.table({ left, right, top, bottom, canvasWidth, canvasHeight, width, height, startX, startY, circle, sx, sy, dx, dy, sWidth, sHeight, dWidth, dHeight });
ctx.drawImage(this.elements.preview, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
if (circle) {
ctx.fillStyle = '#fff';
ctx.globalCompositeOperation = 'destination-in';
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, canvas.width / 2, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
return canvas;
}
function _getHtmlResult(data) {
var points = data.points,
div = document.createElement('div'),
img = document.createElement('img'),
width = points[2] - points[0],
height = points[3] - points[1];
addClass(div, 'croppie-result');
div.appendChild(img);
css(img, {
left: (-1 * points[0]) + 'px',
top: (-1 * points[1]) + 'px'
});
img.src = data.url;
css(div, {
width: width + 'px',
height: height + 'px'
});
return div;
}
function _getBase64Result(data) {
return _getCanvas.call(this, data).toDataURL(data.format, data.quality);
}
function _getBlobResult(data) {
var self = this;
return new Promise(function (resolve) {
_getCanvas.call(self, data).toBlob(function (blob) {
resolve(blob);
}, data.format, data.quality);
});
}
function _replaceImage(img) {
if (this.elements.img.parentNode) {
Array.prototype.forEach.call(this.elements.img.classList, function(c) { img.classList.add(c); });
this.elements.img.parentNode.replaceChild(img, this.elements.img);
this.elements.preview = img; // if the img is attached to the DOM, they're not using the canvas
}
this.elements.img = img;
}
function _bind(options, cb) {
var self = this,
url,
points = [],
zoom = null,
hasExif = _hasExif.call(self);
if (typeof (options) === 'string') {
url = options;
options = {};
}
else if (Array.isArray(options)) {
points = options.slice();
}
else if (typeof (options) === 'undefined' && self.data.url) { //refreshing
_updatePropertiesFromImage.call(self);
_triggerUpdate.call(self);
return null;
}
else {
url = options.url;
points = options.points || [];
zoom = typeof(options.zoom) === 'undefined' ? null : options.zoom;
}
self.data.bound = false;
self.data.url = url || self.data.url;
self.data.boundZoom = zoom;
return loadImage(url, hasExif).then(function (img) {
_replaceImage.call(self, img);
if (!points.length) {
var natDim = naturalImageDimensions(img);
var rect = self.elements.viewport.getBoundingClientRect();
var aspectRatio = rect.width / rect.height;
var imgAspectRatio = natDim.width / natDim.height;
var width, height;
if (imgAspectRatio > aspectRatio) {
height = natDim.height;
width = height * aspectRatio;
}
else {
width = natDim.width;
height = natDim.height / aspectRatio;
}
var x0 = (natDim.width - width) / 2;
var y0 = (natDim.height - height) / 2;
var x1 = x0 + width;
var y1 = y0 + height;
self.data.points = [x0, y0, x1, y1];
}
else if (self.options.relative) {
points = [
points[0] * img.naturalWidth / 100,
points[1] * img.naturalHeight / 100,
points[2] * img.naturalWidth / 100,
points[3] * img.naturalHeight / 100
];
}
self.data.points = points.map(function (p) {
return parseFloat(p);
});
if (self.options.useCanvas) {
_transferImageToCanvas.call(self, options.orientation);
}
_updatePropertiesFromImage.call(self);
_triggerUpdate.call(self);
cb && cb();
});
}
function fix(v, decimalPoints) {
return parseFloat(v).toFixed(decimalPoints || 0);
}
function _get() {
var self = this,
imgData = self.elements.preview.getBoundingClientRect(),
vpData = self.elements.viewport.getBoundingClientRect(),
x1 = vpData.left - imgData.left,
y1 = vpData.top - imgData.top,
widthDiff = (vpData.width - self.elements.viewport.offsetWidth) / 2, //border
heightDiff = (vpData.height - self.elements.viewport.offsetHeight) / 2,
x2 = x1 + self.elements.viewport.offsetWidth + widthDiff,
y2 = y1 + self.elements.viewport.offsetHeight + heightDiff,
scale = self._currentZoom;
if (scale === Infinity || isNaN(scale)) {
scale = 1;
}
var max = self.options.enforceBoundary ? 0 : Number.NEGATIVE_INFINITY;
x1 = Math.max(max, x1 / scale);
y1 = Math.max(max, y1 / scale);
x2 = Math.max(max, x2 / scale);
y2 = Math.max(max, y2 / scale);
return {
points: [fix(x1), fix(y1), fix(x2), fix(y2)],
zoom: scale,
orientation: self.data.orientation
};
}
var RESULT_DEFAULTS = {
type: 'canvas',
format: 'png',
quality: 1
},
RESULT_FORMATS = ['jpeg', 'webp', 'png'];
function _result(options) {
var self = this,
data = _get.call(self),
opts = deepExtend(clone(RESULT_DEFAULTS), clone(options)),
resultType = (typeof (options) === 'string' ? options : (opts.type || 'base64')),
size = opts.size || 'viewport',
format = opts.format,
quality = opts.quality,
backgroundColor = opts.backgroundColor,
circle = typeof opts.circle === 'boolean' ? opts.circle : (self.options.viewport.type === 'circle'),
vpRect = self.elements.viewport.getBoundingClientRect(),
ratio = vpRect.width / vpRect.height,
prom;
if (size === 'viewport') {
data.outputWidth = vpRect.width;
data.outputHeight = vpRect.height;
} else if (typeof size === 'object') {
if (size.width && size.height) {
data.outputWidth = size.width;
data.outputHeight = size.height;
} else if (size.width) {
data.outputWidth = size.width;
data.outputHeight = size.width / ratio;
} else if (size.height) {
data.outputWidth = size.height * ratio;
data.outputHeight = size.height;
}
}
if (RESULT_FORMATS.indexOf(format) > -1) {
data.format = 'image/' + format;
data.quality = quality;
}
data.circle = circle;
data.url = self.data.url;
data.backgroundColor = backgroundColor;
prom = new Promise(function (resolve) {
switch(resultType.toLowerCase())
{
case 'rawcanvas':
resolve(_getCanvas.call(self, data));
break;
case 'canvas':
case 'base64':
resolve(_getBase64Result.call(self, data));
break;
case 'blob':
_getBlobResult.call(self, data).then(resolve);
break;
default:
resolve(_getHtmlResult.call(self, data));
break;
}
});
return prom;
}
function _refresh() {
_updatePropertiesFromImage.call(this);
}
function _rotate(deg) {
if (!this.options.useCanvas || !this.options.enableOrientation) {
throw 'Croppie: Cannot rotate without enableOrientation && EXIF.js included';
}
var self = this,
canvas = self.elements.canvas;
self.data.orientation = getExifOffset(self.data.orientation, deg);
drawCanvas(canvas, self.elements.img, self.data.orientation);
_updateCenterPoint.call(self, true);
_updateZoomLimits.call(self);
}
function _destroy() {
var self = this;
self.element.removeChild(self.elements.boundary);
removeClass(self.element, 'croppie-container');
if (self.options.enableZoom) {
self.element.removeChild(self.elements.zoomerWrap);
}
delete self.elements;
}
if (window.jQuery) {
var $ = window.jQuery;
$.fn.croppie = function (opts) {
var ot = typeof opts;
if (ot === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
var singleInst = $(this).data('croppie');
if (opts === 'get') {
return singleInst.get();
}
else if (opts === 'result') {
return singleInst.result.apply(singleInst, args);
}
else if (opts === 'bind') {
return singleInst.bind.apply(singleInst, args);
}
return this.each(function () {
var i = $(this).data('croppie');
if (!i) return;
var method = i[opts];
if ($.isFunction(method)) {
method.apply(i, args);
if (opts === 'destroy') {
$(this).removeData('croppie');
}
}
else {
throw 'Croppie ' + opts + ' method not found';
}
});
}
else {
return this.each(function () {
var i = new Croppie(this, opts);
i.$ = $;
$(this).data('croppie', i);
});
}
};
}
function Croppie(element, opts) {
if (element.className.indexOf('croppie-container') > -1) {
throw new Error("Croppie: Can't initialize croppie more than once");
}
this.element = element;
this.options = deepExtend(clone(Croppie.defaults), opts);
if (this.element.tagName.toLowerCase() === 'img') {
var origImage = this.element;
addClass(origImage, 'cr-original-image');
setAttributes(origImage, {'aria-hidden' : 'true', 'alt' : '' });
var replacementDiv = document.createElement('div');
this.element.parentNode.appendChild(replacementDiv);
replacementDiv.appendChild(origImage);
this.element = replacementDiv;
this.options.url = this.options.url || origImage.src;
}
_create.call(this);
if (this.options.url) {
var bindOpts = {
url: this.options.url,
points: this.options.points
};
delete this.options['url'];
delete this.options['points'];
_bind.call(this, bindOpts);
}
}
Croppie.defaults = {
viewport: {
width: 100,
height: 100,
type: 'square'
},
boundary: { },
orientationControls: {
enabled: true,
leftClass: '',
rightClass: ''
},
resizeControls: {
width: true,
height: true
},
customClass: '',
showZoomer: true,
enableZoom: true,
enableResize: false,
mouseWheelZoom: true,
enableExif: false,
enforceBoundary: true,
enableOrientation: false,
enableKeyMovement: true,
update: function () { }
};
Croppie.globals = {
translate: 'translate3d'
};
deepExtend(Croppie.prototype, {
bind: function (options, cb) {
return _bind.call(this, options, cb);
},
get: function () {
var data = _get.call(this);
var points = data.points;
if (this.options.relative) {
points[0] /= this.elements.img.naturalWidth / 100;
points[1] /= this.elements.img.naturalHeight / 100;
points[2] /= this.elements.img.naturalWidth / 100;
points[3] /= this.elements.img.naturalHeight / 100;
}
return data;
},
result: function (type) {
return _result.call(this, type);
},
refresh: function () {
return _refresh.call(this);
},
setZoom: function (v) {
_setZoomerVal.call(this, v);
dispatchChange(this.elements.zoomer);
},
rotate: function (deg) {
_rotate.call(this, deg);
},
destroy: function () {
return _destroy.call(this);
}
});
return Croppie;
}));
/* global window, Image, jQuery */
/**
* @author 360Learning
* @author Catalin Dogaru (https://github.com/cdog - http://code.tutsplus.com/tutorials/how-to-create-a-jquery-image-cropping-plugin-from-scratch-part-i--net-20994)
* @author Adrien David-Sivelle (https://github.com/AdrienDS - Refactoring, Multiselections & Mobile compatibility)
*/
(function($) {
$.imageArea = function(parent, id) {
var options = parent.options,
$image = parent.$image,
$trigger = parent.$trigger,
$outline,
$selection,
$resizeHandlers = {},
$btDelete,
resizeHorizontally = true,
resizeVertically = true,
selectionOffset = [0, 0],
selectionOrigin = [0, 0],
area = {
id: id,
x: 0,
y: 0,
z: 0,
height: 0,
width: 0
},
blur = function () {
area.z = 0;
refresh("blur");
},
focus = function () {
parent.blurAll();
area.z = 100;
refresh();
},
getData = function () {
return area;
},
fireEvent = function (event) {
$image.trigger(event, [area.id, parent.areas()]);
},
cancelEvent = function (e) {
var event = e || window.event || {};
event.cancelBubble = true;
event.returnValue = false;
event.stopPropagation && event.stopPropagation(); // jshint ignore: line
event.preventDefault && event.preventDefault(); // jshint ignore: line
},
off = function() {
$.each(arguments, function (key, val) {
on(val);
});
},
on = function (type, handler) {
var browserEvent, mobileEvent;
switch (type) {
case "start":
browserEvent = "mousedown";
mobileEvent = "touchstart";
break;
case "move":
browserEvent = "mousemove";
mobileEvent = "touchmove";
break;
case "stop":
browserEvent = "mouseup";
mobileEvent = "touchend";
break;
default:
return;
}
if (handler && jQuery.isFunction(handler)) {
$(window.document).on(browserEvent, handler).on(mobileEvent, handler);
} else {
$(window.document).off(browserEvent).off(mobileEvent);
}
},
updateSelection = function () {
// Update the outline layer
$outline.css({
cursor: "default",
width: area.width,
height: area.height,
left: area.x,
top: area.y,
"z-index": area.z
});
// Update the selection layer
$selection.css({
backgroundPosition : ( - area.x - 1) + "px " + ( - area.y - 1) + "px",
cursor : options.allowMove ? "move" : "default",
width: (area.width - 2 > 0) ? (area.width - 2) : 0,
height: (area.height - 2 > 0) ? (area.height - 2) : 0,
left : area.x + 1,
top : area.y + 1,
"z-index": area.z + 2
});
},
updateResizeHandlers = function (show) {
if (! options.allowResize) {
return;
}
if (show) {
$.each($resizeHandlers, function(name, $handler) {
var top,
left,
semiwidth = Math.round($handler.width() / 2),
semiheight = Math.round($handler.height() / 2),
vertical = name[0],
horizontal = name[name.length - 1];
if (vertical === "n") { // ====== North* ======
top = - semiheight;
} else if (vertical === "s") { // ====== South* ======
top = area.height - semiheight - 1;
} else { // === East & West ===
top = Math.round(area.height / 2) - semiheight - 1;
}
if (horizontal === "e") { // ====== *East ======
left = area.width - semiwidth - 1;
} else if (horizontal === "w") { // ====== *West ======
left = - semiwidth;
} else { // == North & South ==
left = Math.round(area.width / 2) - semiwidth - 1;
}
$handler.css({
display: "block",
left: area.x + left,
top: area.y + top,
"z-index": area.z + 1
});
});
} else {
$(".select-areas-resize-handler").each(function() {
$(this).css({ display: "none" });
});
}
},
updateBtDelete = function (visible) {
if ($btDelete) {
$btDelete.css({
display: visible ? "block" : "none",
left: area.x + area.width + 1,
top: area.y - $btDelete.outerHeight() - 1,
"z-index": area.z + 1
});
}
},
updateCursor = function (cursorType) {
$outline.css({
cursor: cursorType
});
$selection.css({
cursor: cursorType
});
},
refresh = function(sender) {
switch (sender) {
case "startSelection":
parent._refresh();
updateSelection();
updateResizeHandlers();
updateBtDelete(true);
break;
case "pickSelection":
case "pickResizeHandler":
updateResizeHandlers();
break;
case "resizeSelection":
updateSelection();
updateResizeHandlers();
updateCursor("crosshair");
updateBtDelete(true);
break;
case "moveSelection":
updateSelection();
updateResizeHandlers();
updateCursor("move");
updateBtDelete(true);
break;
case "blur":
updateSelection();
updateResizeHandlers();
updateBtDelete();
break;
//case "releaseSelection":
default:
updateSelection();
updateResizeHandlers(true);
updateBtDelete(true);
}
},
startSelection = function (event) {
cancelEvent(event);
// Reset the selection size
area.width = options.minSize[0];
area.height = options.minSize[1];
focus();
on("move", resizeSelection);
on("stop", releaseSelection);
// Get the selection origin
selectionOrigin = getMousePosition(event);
if (selectionOrigin[0] + area.width > $image.width()) {
selectionOrigin[0] = $image.width() - area.width;
}
if (selectionOrigin[1] + area.height > $image.height()) {
selectionOrigin[1] = $image.height() - area.height;
}
// And set its position
area.x = selectionOrigin[0];
area.y = selectionOrigin[1];
refresh("startSelection");
},
pickSelection = function (event) {
cancelEvent(event);
focus();
on("move", moveSelection);
on("stop", releaseSelection);
var mousePosition = getMousePosition(event);
// Get the selection offset relative to the mouse position
selectionOffset[0] = mousePosition[0] - area.x;
selectionOffset[1] = mousePosition[1] - area.y;
refresh("pickSelection");
},
pickResizeHandler = function (event) {
cancelEvent(event);
focus();
var card = event.target.className.split(" ")[1];
if (card[card.length - 1] === "w") {
selectionOrigin[0] += area.width;
area.x = selectionOrigin[0] - area.width;
}
if (card[0] === "n") {
selectionOrigin[1] += area.height;
area.y = selectionOrigin[1] - area.height;
}
if (card === "n" || card === "s") {
resizeHorizontally = false;
} else if (card === "e" || card === "w") {
resizeVertically = false;
}
on("move", resizeSelection);
on("stop", releaseSelection);
refresh("pickResizeHandler");
},
resizeSelection = function (event) {
cancelEvent(event);
focus();
var mousePosition = getMousePosition(event);
// Get the selection size
var height = mousePosition[1] - selectionOrigin[1],
width = mousePosition[0] - selectionOrigin[0];
// If the selection size is smaller than the minimum size set it to minimum size
if (Math.abs(width) < options.minSize[0]) {
width = (width >= 0) ? options.minSize[0] : - options.minSize[0];
}
if (Math.abs(height) < options.minSize[1]) {
height = (height >= 0) ? options.minSize[1] : - options.minSize[1];
}
// Test if the selection size exceeds the image bounds
if (selectionOrigin[0] + width < 0 || selectionOrigin[0] + width > $image.width()) {
width = - width;
}
if (selectionOrigin[1] + height < 0 || selectionOrigin[1] + height > $image.height()) {
height = - height;
}
// Test if the selection size is bigger than the maximum size (ignored if minSize > maxSize)
if (options.maxSize[0] > options.minSize[0] && options.maxSize[1] > options.minSize[1]) {
if (Math.abs(width) > options.maxSize[0]) {
width = (width >= 0) ? options.maxSize[0] : - options.maxSize[0];
}
if (Math.abs(height) > options.maxSize[1]) {
height = (height >= 0) ? options.maxSize[1] : - options.maxSize[1];
}
}
// Set the selection size
if (resizeHorizontally) {
area.width = width;
}
if (resizeVertically) {
area.height = height;
}
// If any aspect ratio is specified
if (options.aspectRatio) {
// Calculate the new width and height
if ((width > 0 && height > 0) || (width < 0 && height < 0)) {
if (resizeHorizontally) {
height = Math.round(width / options.aspectRatio);
} else {
width = Math.round(height * options.aspectRatio);
}
} else {
if (resizeHorizontally) {
height = - Math.round(width / options.aspectRatio);
} else {
width = - Math.round(height * options.aspectRatio);
}
}
// Test if the new size exceeds the image bounds
if (selectionOrigin[0] + width > $image.width()) {
width = $image.width() - selectionOrigin[0];
height = (height > 0) ? Math.round(width / options.aspectRatio) : - Math.round(width / options.aspectRatio);
}
if (selectionOrigin[1] + height < 0) {
height = - selectionOrigin[1];
width = (width > 0) ? - Math.round(height * options.aspectRatio) : Math.round(height * options.aspectRatio);
}
if (selectionOrigin[1] + height > $image.height()) {
height = $image.height() - selectionOrigin[1];
width = (width > 0) ? Math.round(height * options.aspectRatio) : - Math.round(height * options.aspectRatio);
}
// Set the selection size
area.width = width;
area.height = height;
}
if (area.width < 0) {
area.width = Math.abs(area.width);
area.x = selectionOrigin[0] - area.width;
} else {
area.x = selectionOrigin[0];
}
if (area.height < 0) {
area.height = Math.abs(area.height);
area.y = selectionOrigin[1] - area.height;
} else {
area.y = selectionOrigin[1];
}
fireEvent("changing");
refresh("resizeSelection");
},
moveSelection = function (event) {
cancelEvent(event);
if (! options.allowMove) {
return;
}
focus();
var mousePosition = getMousePosition(event);
moveTo({
x: mousePosition[0] - selectionOffset[0],
y: mousePosition[1] - selectionOffset[1]
});
fireEvent("changing");
},
moveTo = function (point) {
// Set the selection position on the x-axis relative to the bounds
// of the image
if (point.x > 0) {
if (point.x + area.width < $image.width()) {
area.x = point.x;
} else {
area.x = $image.width() - area.width;
}
} else {
area.x = 0;
}
// Set the selection position on the y-axis relative to the bounds
// of the image
if (point.y > 0) {
if (point.y + area.height < $image.height()) {
area.y = point.y;
} else {
area.y = $image.height() - area.height;
}
} else {
area.y = 0;
}
refresh("moveSelection");
},
releaseSelection = function (event) {
cancelEvent(event);
off("move", "stop");
// Update the selection origin
selectionOrigin[0] = area.x;
selectionOrigin[1] = area.y;
// Reset the resize constraints
resizeHorizontally = true;
resizeVertically = true;
fireEvent("changed");
refresh("releaseSelection");
},
deleteSelection = function (event) {
cancelEvent(event);
$selection.remove();
$outline.remove();
$.each($resizeHandlers, function(card, $handler) {
$handler.remove();
});
$btDelete.remove();
parent._remove(id);
fireEvent("changed");
},
getElementOffset = function (object) {
var offset = $(object).offset();
return [offset.left, offset.top];
},
getMousePosition = function (event) {
var imageOffset = getElementOffset($image);
if (! event.pageX) {
if (event.originalEvent) {
event = event.originalEvent;
}
if(event.changedTouches) {
event = event.changedTouches[0];
}
if(event.touches) {
event = event.touches[0];
}
}
var x = event.pageX - imageOffset[0],
y = event.pageY - imageOffset[1];
x = (x < 0) ? 0 : (x > $image.width()) ? $image.width() : x;
y = (y < 0) ? 0 : (y > $image.height()) ? $image.height() : y;
return [x, y];
};
// Initialize an outline layer and place it above the trigger layer
$outline = $("<div class=\"select-areas-outline\" />")
.css({
opacity : options.outlineOpacity,
position : "absolute"
})
.insertAfter($trigger);
// Initialize a selection layer and place it above the outline layer
$selection = $("<div />")
.addClass("select-areas-background-area")
.css({
background : "#fff url(" + $image.attr("src") + ") no-repeat",
backgroundSize : $image.width() + "px",
position : "absolute"
})
.insertAfter($outline);
// Initialize all handlers
if (options.allowResize) {
$.each(["nw", "n", "ne", "e", "se", "s", "sw", "w"], function (key, card) {
$resizeHandlers[card] = $("<div class=\"select-areas-resize-handler " + card + "\"/>")
.css({
opacity : 0.5,
position : "absolute",
cursor : card + "-resize"
})
.insertAfter($selection)
.mousedown(pickResizeHandler)
.bind("touchstart", pickResizeHandler);
});
}
// initialize delete button
if (options.allowDelete) {
var bindToDelete = function ($obj) {
$obj.click(deleteSelection)
.bind("touchstart", deleteSelection)
.bind("tap", deleteSelection);
return $obj;
};
$btDelete = bindToDelete($("<div class=\"delete-area\" />"))
.append(bindToDelete($("<div class=\"select-areas-delete-area\" />")))
.insertAfter($selection);
}
if (options.allowMove) {
$selection.mousedown(pickSelection).bind("touchstart", pickSelection);
}
focus();
return {
getData: getData,
startSelection: startSelection,
deleteSelection: deleteSelection,
options: options,
blur: blur,
focus: focus,
nudge: function (point) {
point.x = area.x;
point.y = area.y;
if (point.d) {
point.y = area.y + point.d;
}
if (point.u) {
point.y = area.y - point.u;
}
if (point.l) {
point.x = area.x - point.l;
}
if (point.r) {
point.x = area.x + point.r;
}
moveTo(point);
fireEvent("changed");
},
set: function (dimensions, silent) {
area = $.extend(area, dimensions);
selectionOrigin[0] = area.x;
selectionOrigin[1] = area.y;
if (! silent) {
fireEvent("changed");
}
},
contains: function (point) {
return (point.x >= area.x) && (point.x <= area.x + area.width) &&
(point.y >= area.y) && (point.y <= area.y + area.height);
}
};
};
$.imageSelectAreas = function() { };
$.imageSelectAreas.prototype.init = function (object, customOptions) {
var that = this,
defaultOptions = {
allowEdit: true,
allowMove: true,
allowResize: true,
allowSelect: true,
allowDelete: true,
allowNudge: true,
aspectRatio: 0,
minSize: [0, 0],
maxSize: [0, 0],
width: 0,
maxAreas: 0,
outlineOpacity: 0.5,
overlayOpacity: 0.5,
areas: [],
onChanging: null,
onChanged: null
};
this.options = $.extend(defaultOptions, customOptions);
if (! this.options.allowEdit) {
this.options.allowSelect = this.options.allowMove = this.options.allowResize = this.options.allowDelete = false;
}
this._areas = {};
// Initialize the image layer
this.$image = $(object);
this.ratio = 1;
if (this.options.width && this.$image.width() && this.options.width !== this.$image.width()) {
this.ratio = this.options.width / this.$image.width();
this.$image.width(this.options.width);
}
if (this.options.onChanging) {
this.$image.on("changing", this.options.onChanging);
}
if (this.options.onChanged) {
this.$image.on("changed", this.options.onChanged);
}
if (this.options.onLoaded) {
this.$image.on("loaded", this.options.onLoaded);
}
// Initialize an image holder
this.$holder = $("<div />")
.css({
position : "relative",
width: this.$image.width(),
height: this.$image.height()
});
// Wrap the holder around the image
this.$image.wrap(this.$holder)
.css({
position : "absolute"
});
// Initialize an overlay layer and place it above the image
this.$overlay = $("<div class=\"select-areas-overlay\" />")
.css({
opacity : this.options.overlayOpacity,
position : "absolute",
width: this.$image.width(),
height: this.$image.height()
})
.insertAfter(this.$image);
// Initialize a trigger layer and place it above the overlay layer
this.$trigger = $("<div />")
.css({
backgroundColor : "#000000",
opacity : 0,
position : "absolute",
width: this.$image.width(),
height: this.$image.height()
})
.insertAfter(this.$overlay);
$.each(this.options.areas, function (key, area) {
that._add(area, true);
});
this.blurAll();
this._refresh();
if (this.options.allowSelect) {
// Bind an event handler to the "mousedown" event of the trigger layer
this.$trigger.mousedown($.proxy(this.newArea, this)).on("touchstart", $.proxy(this.newArea, this));
}
if (this.options.allowNudge) {
$('html').keydown(function (e) { // move selection with arrow keys
var codes = {
37: "l",
38: "u",
39: "r",
40: "d"
},
direction = codes[e.which],
selectedArea;
if (direction) {
that._eachArea(function (area) {
if (area.getData().z === 100) {
selectedArea = area;
return false;
}
});
if (selectedArea) {
var move = {};
move[direction] = 1;
selectedArea.nudge(move);
}
}
});
}
};
$.imageSelectAreas.prototype._refresh = function () {
var nbAreas = this.areas().length;
this.$overlay.css({
display : nbAreas? "block" : "none"
});
if (nbAreas) {
this.$image.addClass("blurred");
} else {
this.$image.removeClass("blurred");
}
this.$trigger.css({
cursor : this.options.allowSelect ? "crosshair" : "default"
});
};
$.imageSelectAreas.prototype._eachArea = function (cb) {
$.each(this._areas, function (id, area) {
if (area) {
return cb(area, id);
}
});
};
$.imageSelectAreas.prototype._remove = function (id) {
delete this._areas[id];
this._refresh();
};
$.imageSelectAreas.prototype.remove = function (id) {
if (this._areas[id]) {
this._areas[id].deleteSelection();
}
};
$.imageSelectAreas.prototype.newArea = function (event) {
var id = -1;
this.blurAll();
if (this.options.maxAreas && this.options.maxAreas <= this.areas().length) {
return id;
}
this._eachArea(function (area, index) {
id = Math.max(id, parseInt(index, 10));
});
id += 1;
this._areas[id] = $.imageArea(this, id);
if (event) {
this._areas[id].startSelection(event);
}
return id;
};
$.imageSelectAreas.prototype.set = function (id, options, silent) {
if (this._areas[id]) {
options.id = id;
this._areas[id].set(options, silent);
this._areas[id].focus();
}
};
$.imageSelectAreas.prototype._add = function (options, silent) {
var id = this.newArea();
this.set(id, options, silent);
};
$.imageSelectAreas.prototype.add = function (options) {
var that = this;
this.blurAll();
if ($.isArray(options)) {
$.each(options, function (key, val) {
that._add(val);
});
} else {
this._add(options);
}
this._refresh();
if (! this.options.allowSelect && ! this.options.allowMove && ! this.options.allowResize && ! this.options.allowDelete) {
this.blurAll();
}
};
$.imageSelectAreas.prototype.reset = function () {
var that = this;
this._eachArea(function (area, id) {
that.remove(id);
});
this._refresh();
};
$.imageSelectAreas.prototype.destroy = function () {
this.reset();
this.$holder.remove();
this.$overlay.remove();
this.$trigger.remove();
this.$image.css("width", "").css("position", "").unwrap();
this.$image.removeData("mainImageSelectAreas");
};
$.imageSelectAreas.prototype.areas = function () {
var ret = [];
this._eachArea(function (area) {
ret.push(area.getData());
});
return ret;
};
$.imageSelectAreas.prototype.relativeAreas = function () {
var areas = this.areas(),
ret = [],
ratio = this.ratio,
scale = function (val) {
return Math.floor(val / ratio);
};
for (var i = 0; i < areas.length; i++) {
ret[i] = $.extend({}, areas[i]);
ret[i].x = scale(ret[i].x);
ret[i].y = scale(ret[i].y);
ret[i].width = scale(ret[i].width);
ret[i].height = scale(ret[i].height);
}
return ret;
};
$.imageSelectAreas.prototype.blurAll = function () {
this._eachArea(function (area) {
area.blur();
});
};
$.imageSelectAreas.prototype.contains = function (point) {
var res = false;
this._eachArea(function (area) {
if (area.contains(point)) {
res = true;
return false;
}
});
return res;
};
$.selectAreas = function(object, options) {
var $object = $(object);
if (! $object.data("mainImageSelectAreas")) {
var mainImageSelectAreas = new $.imageSelectAreas();
mainImageSelectAreas.init(object, options);
$object.data("mainImageSelectAreas", mainImageSelectAreas);
$object.trigger("loaded");
}
return $object.data("mainImageSelectAreas");
};
$.fn.selectAreas = function(customOptions) {
if ( $.imageSelectAreas.prototype[customOptions] ) { // Method call
var ret = $.imageSelectAreas.prototype[ customOptions ].apply( $.selectAreas(this), Array.prototype.slice.call( arguments, 1 ));
return typeof ret === "undefined" ? this : ret;
} else if ( typeof customOptions === "object" || ! customOptions ) { // Initialization
//Iterate over each object
this.each(function() {
var currentObject = this,
image = new Image();
// And attach selectAreas when the object is loaded
image.onload = function() {
$.selectAreas(currentObject, customOptions);
};
// Reset the src because cached images don"t fire load sometimes
image.src = currentObject.src;
});
return this;
} else {
$.error( "Method " + customOptions + " does not exist on jQuery.selectAreas" );
}
};
}) (jQuery);
.darkroom-container{position:relative}.darkroom-image-container{top:0;left:0}.darkroom-toolbar{display:block;position:absolute;top:-45px;left:0;background:#444;height:40px;min-width:40px;z-index:99;border-radius:2px;white-space:nowrap;padding:0 5px}.darkroom-toolbar:before{content:"";position:absolute;bottom:-7px;left:20px;width:0;height:0;border-left:7px solid transparent;border-right:7px solid transparent;border-top:7px solid #444}.darkroom-button-group{display:inline-block;margin:0;padding:0}.darkroom-button-group:last-child{border-right:none}.darkroom-button{box-sizing:border-box;background:transparent;border:none;outline:none;padding:2px 0 0 0;width:40px;height:40px}.darkroom-button:hover{cursor:pointer;background:#555}.darkroom-button:active{cursor:pointer;background:#333}.darkroom-button:disabled .darkroom-icon{fill:#666}.darkroom-button:disabled:hover{cursor:default;background:transparent}.darkroom-button.darkroom-button-active .darkroom-icon{fill:#33b5e5}.darkroom-button.darkroom-button-hidden{display:none}.darkroom-button.darkroom-button-success .darkroom-icon{fill:#99cc00}.darkroom-button.darkroom-button-warning .darkroom-icon{fill:#FFBB33}.darkroom-button.darkroom-button-danger .darkroom-icon{fill:#FF4444}.darkroom-icon{width:24px;height:24px;fill:#fff}
.select-areas-overlay {
background-color: #000;
overflow: hidden;
position: absolute;
}
.blurred {
filter: url("/filters.svg#blur3px");
-webkit-filter: blur(3px);
-moz-filter: blur(3px);
-o-filter: blur(3px);
filter: blur(3px);
}
.select-areas-outline {
background: #fff url('outline.gif');
overflow: hidden;
}
.select-areas-resize-handler {
background-color: #000;
border: 1px #fff solid;
height: 8px;
width: 8px;
overflow: hidden;
}
.select-areas-delete-area {
background: url('bt-delete.png');
cursor: pointer;
height: 16px;
width: 16px;
}
.delete-area {
position: absolute;
cursor: pointer;
padding: 5px;
}
.select-areas-overlay {
background: none;
}
.select-areas-outline {
background: none;
visibility: hidden;
}
.select-areas-outline {
visibility: hidden;
}
.select-areas-background-area {
background: none !important;
margin: -1px 0 0 -1px;
border: 2px solid green;
}
.blurred {
filter: none;
-webkit-filter: none;
-moz-filter: none;
-o-filter: none;
}
/* global window, Image, jQuery */
/**
* @author 360Learning
* @author Catalin Dogaru (https://github.com/cdog - http://code.tutsplus.com/tutorials/how-to-create-a-jquery-image-cropping-plugin-from-scratch-part-i--net-20994)
* @author Adrien David-Sivelle (https://github.com/AdrienDS - Refactoring, Multiselections & Mobile compatibility)
*/
(function($) {
$.imageArea = function(parent, id) {
var options = parent.options,
$image = parent.$image,
$trigger = parent.$trigger,
$outline,
$selection,
$resizeHandlers = {},
$btDelete,
resizeHorizontally = true,
resizeVertically = true,
selectionOffset = [0, 0],
selectionOrigin = [0, 0],
area = {
id: id,
x: 0,
y: 0,
z: 0,
height: 0,
width: 0
},
blur = function () {
area.z = 0;
refresh("blur");
},
focus = function () {
parent.blurAll();
area.z = 100;
refresh();
},
getData = function () {
return area;
},
fireEvent = function (event) {
$image.trigger(event, [area.id, parent.areas()]);
},
cancelEvent = function (e) {
var event = e || window.event || {};
event.cancelBubble = true;
event.returnValue = false;
event.stopPropagation && event.stopPropagation(); // jshint ignore: line
event.preventDefault && event.preventDefault(); // jshint ignore: line
},
off = function() {
$.each(arguments, function (key, val) {
on(val);
});
},
on = function (type, handler) {
var browserEvent, mobileEvent;
switch (type) {
case "start":
browserEvent = "mousedown";
mobileEvent = "touchstart";
break;
case "move":
browserEvent = "mousemove";
mobileEvent = "touchmove";
break;
case "stop":
browserEvent = "mouseup";
mobileEvent = "touchend";
break;
default:
return;
}
if (handler && jQuery.isFunction(handler)) {
$(window.document).on(browserEvent, handler).on(mobileEvent, handler);
} else {
$(window.document).off(browserEvent).off(mobileEvent);
}
},
updateSelection = function () {
// Update the outline layer
$outline.css({
cursor: "default",
width: area.width,
height: area.height,
left: area.x,
top: area.y,
"z-index": area.z
});
// Update the selection layer
$selection.css({
backgroundPosition : ( - area.x - 1) + "px " + ( - area.y - 1) + "px",
cursor : options.allowMove ? "move" : "default",
width: (area.width - 2 > 0) ? (area.width - 2) : 0,
height: (area.height - 2 > 0) ? (area.height - 2) : 0,
left : area.x + 1,
top : area.y + 1,
"z-index": area.z + 2
});
},
updateResizeHandlers = function (show) {
if (! options.allowResize) {
return;
}
if (show) {
$.each($resizeHandlers, function(name, $handler) {
var top,
left,
semiwidth = Math.round($handler.width() / 2),
semiheight = Math.round($handler.height() / 2),
vertical = name[0],
horizontal = name[name.length - 1];
if (vertical === "n") { // ====== North* ======
top = - semiheight;
} else if (vertical === "s") { // ====== South* ======
top = area.height - semiheight - 1;
} else { // === East & West ===
top = Math.round(area.height / 2) - semiheight - 1;
}
if (horizontal === "e") { // ====== *East ======
left = area.width - semiwidth - 1;
} else if (horizontal === "w") { // ====== *West ======
left = - semiwidth;
} else { // == North & South ==
left = Math.round(area.width / 2) - semiwidth - 1;
}
$handler.css({
display: "block",
left: area.x + left,
top: area.y + top,
"z-index": area.z + 1
});
});
} else {
$(".select-areas-resize-handler").each(function() {
$(this).css({ display: "none" });
});
}
},
updateBtDelete = function (visible) {
if ($btDelete) {
$btDelete.css({
display: visible ? "block" : "none",
left: area.x + area.width + 1,
top: area.y - $btDelete.outerHeight() - 1,
"z-index": area.z + 1
});
}
},
updateCursor = function (cursorType) {
$outline.css({
cursor: cursorType
});
$selection.css({
cursor: cursorType
});
},
refresh = function(sender) {
switch (sender) {
case "startSelection":
parent._refresh();
updateSelection();
updateResizeHandlers();
updateBtDelete(true);
break;
case "pickSelection":
case "pickResizeHandler":
updateResizeHandlers();
break;
case "resizeSelection":
updateSelection();
updateResizeHandlers();
updateCursor("crosshair");
updateBtDelete(true);
break;
case "moveSelection":
updateSelection();
updateResizeHandlers();
updateCursor("move");
updateBtDelete(true);
break;
case "blur":
updateSelection();
updateResizeHandlers();
updateBtDelete();
break;
//case "releaseSelection":
default:
updateSelection();
updateResizeHandlers(true);
updateBtDelete(true);
}
},
startSelection = function (event) {
cancelEvent(event);
// Reset the selection size
area.width = options.minSize[0];
area.height = options.minSize[1];
focus();
on("move", resizeSelection);
on("stop", releaseSelection);
// Get the selection origin
selectionOrigin = getMousePosition(event);
if (selectionOrigin[0] + area.width > $image.width()) {
selectionOrigin[0] = $image.width() - area.width;
}
if (selectionOrigin[1] + area.height > $image.height()) {
selectionOrigin[1] = $image.height() - area.height;
}
// And set its position
area.x = selectionOrigin[0];
area.y = selectionOrigin[1];
refresh("startSelection");
},
pickSelection = function (event) {
cancelEvent(event);
focus();
on("move", moveSelection);
on("stop", releaseSelection);
var mousePosition = getMousePosition(event);
// Get the selection offset relative to the mouse position
selectionOffset[0] = mousePosition[0] - area.x;
selectionOffset[1] = mousePosition[1] - area.y;
refresh("pickSelection");
},
pickResizeHandler = function (event) {
cancelEvent(event);
focus();
var card = event.target.className.split(" ")[1];
if (card[card.length - 1] === "w") {
selectionOrigin[0] += area.width;
area.x = selectionOrigin[0] - area.width;
}
if (card[0] === "n") {
selectionOrigin[1] += area.height;
area.y = selectionOrigin[1] - area.height;
}
if (card === "n" || card === "s") {
resizeHorizontally = false;
} else if (card === "e" || card === "w") {
resizeVertically = false;
}
on("move", resizeSelection);
on("stop", releaseSelection);
refresh("pickResizeHandler");
},
resizeSelection = function (event) {
cancelEvent(event);
focus();
var mousePosition = getMousePosition(event);
// Get the selection size
var height = mousePosition[1] - selectionOrigin[1],
width = mousePosition[0] - selectionOrigin[0];
// If the selection size is smaller than the minimum size set it to minimum size
if (Math.abs(width) < options.minSize[0]) {
width = (width >= 0) ? options.minSize[0] : - options.minSize[0];
}
if (Math.abs(height) < options.minSize[1]) {
height = (height >= 0) ? options.minSize[1] : - options.minSize[1];
}
// Test if the selection size exceeds the image bounds
if (selectionOrigin[0] + width < 0 || selectionOrigin[0] + width > $image.width()) {
width = - width;
}
if (selectionOrigin[1] + height < 0 || selectionOrigin[1] + height > $image.height()) {
height = - height;
}
// Test if the selection size is bigger than the maximum size (ignored if minSize > maxSize)
if (options.maxSize[0] > options.minSize[0] && options.maxSize[1] > options.minSize[1]) {
if (Math.abs(width) > options.maxSize[0]) {
width = (width >= 0) ? options.maxSize[0] : - options.maxSize[0];
}
if (Math.abs(height) > options.maxSize[1]) {
height = (height >= 0) ? options.maxSize[1] : - options.maxSize[1];
}
}
// Set the selection size
if (resizeHorizontally) {
area.width = width;
}
if (resizeVertically) {
area.height = height;
}
// If any aspect ratio is specified
if (options.aspectRatio) {
// Calculate the new width and height
if ((width > 0 && height > 0) || (width < 0 && height < 0)) {
if (resizeHorizontally) {
height = Math.round(width / options.aspectRatio);
} else {
width = Math.round(height * options.aspectRatio);
}
} else {
if (resizeHorizontally) {
height = - Math.round(width / options.aspectRatio);
} else {
width = - Math.round(height * options.aspectRatio);
}
}
// Test if the new size exceeds the image bounds
if (selectionOrigin[0] + width > $image.width()) {
width = $image.width() - selectionOrigin[0];
height = (height > 0) ? Math.round(width / options.aspectRatio) : - Math.round(width / options.aspectRatio);
}
if (selectionOrigin[1] + height < 0) {
height = - selectionOrigin[1];
width = (width > 0) ? - Math.round(height * options.aspectRatio) : Math.round(height * options.aspectRatio);
}
if (selectionOrigin[1] + height > $image.height()) {
height = $image.height() - selectionOrigin[1];
width = (width > 0) ? Math.round(height * options.aspectRatio) : - Math.round(height * options.aspectRatio);
}
// Set the selection size
area.width = width;
area.height = height;
}
if (area.width < 0) {
area.width = Math.abs(area.width);
area.x = selectionOrigin[0] - area.width;
} else {
area.x = selectionOrigin[0];
}
if (area.height < 0) {
area.height = Math.abs(area.height);
area.y = selectionOrigin[1] - area.height;
} else {
area.y = selectionOrigin[1];
}
fireEvent("changing");
refresh("resizeSelection");
},
moveSelection = function (event) {
cancelEvent(event);
if (! options.allowMove) {
return;
}
focus();
var mousePosition = getMousePosition(event);
moveTo({
x: mousePosition[0] - selectionOffset[0],
y: mousePosition[1] - selectionOffset[1]
});
fireEvent("changing");
},
moveTo = function (point) {
// Set the selection position on the x-axis relative to the bounds
// of the image
if (point.x > 0) {
if (point.x + area.width < $image.width()) {
area.x = point.x;
} else {
area.x = $image.width() - area.width;
}
} else {
area.x = 0;
}
// Set the selection position on the y-axis relative to the bounds
// of the image
if (point.y > 0) {
if (point.y + area.height < $image.height()) {
area.y = point.y;
} else {
area.y = $image.height() - area.height;
}
} else {
area.y = 0;
}
refresh("moveSelection");
},
releaseSelection = function (event) {
cancelEvent(event);
off("move", "stop");
// Update the selection origin
selectionOrigin[0] = area.x;
selectionOrigin[1] = area.y;
// Reset the resize constraints
resizeHorizontally = true;
resizeVertically = true;
fireEvent("changed");
refresh("releaseSelection");
},
deleteSelection = function (event) {
cancelEvent(event);
$selection.remove();
$outline.remove();
$.each($resizeHandlers, function(card, $handler) {
$handler.remove();
});
$btDelete.remove();
parent._remove(id);
fireEvent("changed");
},
getElementOffset = function (object) {
var offset = $(object).offset();
return [offset.left, offset.top];
},
getMousePosition = function (event) {
var imageOffset = getElementOffset($image);
if (! event.pageX) {
if (event.originalEvent) {
event = event.originalEvent;
}
if(event.changedTouches) {
event = event.changedTouches[0];
}
if(event.touches) {
event = event.touches[0];
}
}
var x = event.pageX - imageOffset[0],
y = event.pageY - imageOffset[1];
x = (x < 0) ? 0 : (x > $image.width()) ? $image.width() : x;
y = (y < 0) ? 0 : (y > $image.height()) ? $image.height() : y;
return [x, y];
};
// Initialize an outline layer and place it above the trigger layer
$outline = $("<div class=\"select-areas-outline\" />")
.css({
opacity : options.outlineOpacity,
position : "absolute"
})
.insertAfter($trigger);
// Initialize a selection layer and place it above the outline layer
$selection = $("<div />")
.addClass("select-areas-background-area")
.css({
background : "#fff url(" + $image.attr("src") + ") no-repeat",
backgroundSize : $image.width() + "px",
position : "absolute"
})
.insertAfter($outline);
// Initialize all handlers
if (options.allowResize) {
$.each(["nw", "n", "ne", "e", "se", "s", "sw", "w"], function (key, card) {
$resizeHandlers[card] = $("<div class=\"select-areas-resize-handler " + card + "\"/>")
.css({
opacity : 0.5,
position : "absolute",
cursor : card + "-resize"
})
.insertAfter($selection)
.mousedown(pickResizeHandler)
.bind("touchstart", pickResizeHandler);
});
}
// initialize delete button
if (options.allowDelete) {
var bindToDelete = function ($obj) {
$obj.click(deleteSelection)
.bind("touchstart", deleteSelection)
.bind("tap", deleteSelection);
return $obj;
};
$btDelete = bindToDelete($("<div class=\"delete-area\" />"))
.append(bindToDelete($("<div class=\"select-areas-delete-area\" />")))
.insertAfter($selection);
}
if (options.allowMove) {
$selection.mousedown(pickSelection).bind("touchstart", pickSelection);
}
focus();
return {
getData: getData,
startSelection: startSelection,
deleteSelection: deleteSelection,
options: options,
blur: blur,
focus: focus,
nudge: function (point) {
point.x = area.x;
point.y = area.y;
if (point.d) {
point.y = area.y + point.d;
}
if (point.u) {
point.y = area.y - point.u;
}
if (point.l) {
point.x = area.x - point.l;
}
if (point.r) {
point.x = area.x + point.r;
}
moveTo(point);
fireEvent("changed");
},
set: function (dimensions, silent) {
area = $.extend(area, dimensions);
selectionOrigin[0] = area.x;
selectionOrigin[1] = area.y;
if (! silent) {
fireEvent("changed");
}
},
contains: function (point) {
return (point.x >= area.x) && (point.x <= area.x + area.width) &&
(point.y >= area.y) && (point.y <= area.y + area.height);
}
};
};
$.imageSelectAreas = function() { };
$.imageSelectAreas.prototype.init = function (object, customOptions) {
var that = this,
defaultOptions = {
allowEdit: true,
allowMove: true,
allowResize: true,
allowSelect: true,
allowDelete: true,
allowNudge: true,
aspectRatio: 0,
minSize: [0, 0],
maxSize: [0, 0],
width: 0,
maxAreas: 0,
outlineOpacity: 0.5,
overlayOpacity: 0.5,
areas: [],
onChanging: null,
onChanged: null
};
this.options = $.extend(defaultOptions, customOptions);
if (! this.options.allowEdit) {
this.options.allowSelect = this.options.allowMove = this.options.allowResize = this.options.allowDelete = false;
}
this._areas = {};
// Initialize the image layer
this.$image = $(object);
this.ratio = 1;
if (this.options.width && this.$image.width() && this.options.width !== this.$image.width()) {
this.ratio = this.options.width / this.$image.width();
this.$image.width(this.options.width);
}
if (this.options.onChanging) {
this.$image.on("changing", this.options.onChanging);
}
if (this.options.onChanged) {
this.$image.on("changed", this.options.onChanged);
}
if (this.options.onLoaded) {
this.$image.on("loaded", this.options.onLoaded);
}
// Initialize an image holder
this.$holder = $("<div />")
.css({
position : "relative",
width: this.$image.width(),
height: this.$image.height()
});
// Wrap the holder around the image
this.$image.wrap(this.$holder)
.css({
position : "absolute"
});
// Initialize an overlay layer and place it above the image
this.$overlay = $("<div class=\"select-areas-overlay\" />")
.css({
opacity : this.options.overlayOpacity,
position : "absolute",
width: this.$image.width(),
height: this.$image.height()
})
.insertAfter(this.$image);
// Initialize a trigger layer and place it above the overlay layer
this.$trigger = $("<div />")
.css({
backgroundColor : "#000000",
opacity : 0,
position : "absolute",
width: this.$image.width(),
height: this.$image.height()
})
.insertAfter(this.$overlay);
$.each(this.options.areas, function (key, area) {
that._add(area, true);
});
this.blurAll();
this._refresh();
if (this.options.allowSelect) {
// Bind an event handler to the "mousedown" event of the trigger layer
this.$trigger.mousedown($.proxy(this.newArea, this)).on("touchstart", $.proxy(this.newArea, this));
}
if (this.options.allowNudge) {
$('html').keydown(function (e) { // move selection with arrow keys
var codes = {
37: "l",
38: "u",
39: "r",
40: "d"
},
direction = codes[e.which],
selectedArea;
if (direction) {
that._eachArea(function (area) {
if (area.getData().z === 100) {
selectedArea = area;
return false;
}
});
if (selectedArea) {
var move = {};
move[direction] = 1;
selectedArea.nudge(move);
}
}
});
}
};
$.imageSelectAreas.prototype._refresh = function () {
var nbAreas = this.areas().length;
this.$overlay.css({
display : nbAreas? "block" : "none"
});
if (nbAreas) {
this.$image.addClass("blurred");
} else {
this.$image.removeClass("blurred");
}
this.$trigger.css({
cursor : this.options.allowSelect ? "crosshair" : "default"
});
};
$.imageSelectAreas.prototype._eachArea = function (cb) {
$.each(this._areas, function (id, area) {
if (area) {
return cb(area, id);
}
});
};
$.imageSelectAreas.prototype._remove = function (id) {
delete this._areas[id];
this._refresh();
};
$.imageSelectAreas.prototype.remove = function (id) {
if (this._areas[id]) {
this._areas[id].deleteSelection();
}
};
$.imageSelectAreas.prototype.newArea = function (event) {
var id = -1;
this.blurAll();
if (this.options.maxAreas && this.options.maxAreas <= this.areas().length) {
return id;
}
this._eachArea(function (area, index) {
id = Math.max(id, parseInt(index, 10));
});
id += 1;
this._areas[id] = $.imageArea(this, id);
if (event) {
this._areas[id].startSelection(event);
}
return id;
};
$.imageSelectAreas.prototype.set = function (id, options, silent) {
if (this._areas[id]) {
options.id = id;
this._areas[id].set(options, silent);
this._areas[id].focus();
}
};
$.imageSelectAreas.prototype._add = function (options, silent) {
var id = this.newArea();
this.set(id, options, silent);
};
$.imageSelectAreas.prototype.add = function (options) {
var that = this;
this.blurAll();
if ($.isArray(options)) {
$.each(options, function (key, val) {
that._add(val);
});
} else {
this._add(options);
}
this._refresh();
if (! this.options.allowSelect && ! this.options.allowMove && ! this.options.allowResize && ! this.options.allowDelete) {
this.blurAll();
}
};
$.imageSelectAreas.prototype.reset = function () {
var that = this;
this._eachArea(function (area, id) {
that.remove(id);
});
this._refresh();
};
$.imageSelectAreas.prototype.destroy = function () {
this.reset();
this.$holder.remove();
this.$overlay.remove();
this.$trigger.remove();
this.$image.css("width", "").css("position", "").unwrap();
this.$image.removeData("mainImageSelectAreas");
};
$.imageSelectAreas.prototype.areas = function () {
var ret = [];
this._eachArea(function (area) {
ret.push(area.getData());
});
return ret;
};
$.imageSelectAreas.prototype.relativeAreas = function () {
var areas = this.areas(),
ret = [],
ratio = this.ratio,
scale = function (val) {
return Math.floor(val / ratio);
};
for (var i = 0; i < areas.length; i++) {
ret[i] = $.extend({}, areas[i]);
ret[i].x = scale(ret[i].x);
ret[i].y = scale(ret[i].y);
ret[i].width = scale(ret[i].width);
ret[i].height = scale(ret[i].height);
}
return ret;
};
$.imageSelectAreas.prototype.blurAll = function () {
this._eachArea(function (area) {
area.blur();
});
};
$.imageSelectAreas.prototype.contains = function (point) {
var res = false;
this._eachArea(function (area) {
if (area.contains(point)) {
res = true;
return false;
}
});
return res;
};
$.selectAreas = function(object, options) {
var $object = $(object);
if (! $object.data("mainImageSelectAreas")) {
var mainImageSelectAreas = new $.imageSelectAreas();
mainImageSelectAreas.init(object, options);
$object.data("mainImageSelectAreas", mainImageSelectAreas);
$object.trigger("loaded");
}
return $object.data("mainImageSelectAreas");
};
$.fn.selectAreas = function(customOptions) {
if ( $.imageSelectAreas.prototype[customOptions] ) { // Method call
var ret = $.imageSelectAreas.prototype[ customOptions ].apply( $.selectAreas(this), Array.prototype.slice.call( arguments, 1 ));
return typeof ret === "undefined" ? this : ret;
} else if ( typeof customOptions === "object" || ! customOptions ) { // Initialization
//Iterate over each object
this.each(function() {
var currentObject = this,
image = new Image();
// And attach selectAreas when the object is loaded
image.onload = function() {
$.selectAreas(currentObject, customOptions);
};
// Reset the src because cached images don"t fire load sometimes
image.src = currentObject.src;
});
return this;
} else {
$.error( "Method " + customOptions + " does not exist on jQuery.selectAreas" );
}
};
}) (jQuery);
/* global window, Image, jQuery */
/**
* @author 360Learning
* @author Catalin Dogaru (https://github.com/cdog - http://code.tutsplus.com/tutorials/how-to-create-a-jquery-image-cropping-plugin-from-scratch-part-i--net-20994)
* @author Adrien David-Sivelle (https://github.com/AdrienDS - Refactoring, Multiselections & Mobile compatibility)
*/
(function($) {
$.imageArea = function(parent, id) {
var options = parent.options,
$image = parent.$image,
$trigger = parent.$trigger,
$outline,
$selection,
$resizeHandlers = {},
$btDelete,
resizeHorizontally = true,
resizeVertically = true,
selectionOffset = [0, 0],
selectionOrigin = [0, 0],
area = {
id: id,
x: 0,
y: 0,
z: 0,
height: 0,
width: 0
},
blur = function () {
area.z = 0;
refresh("blur");
},
focus = function () {
parent.blurAll();
area.z = 100;
refresh();
},
getData = function () {
return area;
},
fireEvent = function (event) {
$image.trigger(event, [area.id, parent.areas()]);
},
cancelEvent = function (e) {
var event = e || window.event || {};
event.cancelBubble = true;
event.returnValue = false;
event.stopPropagation && event.stopPropagation(); // jshint ignore: line
event.preventDefault && event.preventDefault(); // jshint ignore: line
},
off = function() {
$.each(arguments, function (key, val) {
on(val);
});
},
on = function (type, handler) {
var browserEvent, mobileEvent;
switch (type) {
case "start":
browserEvent = "mousedown";
mobileEvent = "touchstart";
break;
case "move":
browserEvent = "mousemove";
mobileEvent = "touchmove";
break;
case "stop":
browserEvent = "mouseup";
mobileEvent = "touchend";
break;
default:
return;
}
if (handler && jQuery.isFunction(handler)) {
$(window.document).on(browserEvent, handler).on(mobileEvent, handler);
} else {
$(window.document).off(browserEvent).off(mobileEvent);
}
},
updateSelection = function () {
// Update the outline layer
$outline.css({
cursor: "default",
width: area.width,
height: area.height,
left: area.x,
top: area.y,
"z-index": area.z
});
// Update the selection layer
$selection.css({
backgroundPosition : ( - area.x - 1) + "px " + ( - area.y - 1) + "px",
cursor : options.allowMove ? "move" : "default",
width: (area.width - 2 > 0) ? (area.width - 2) : 0,
height: (area.height - 2 > 0) ? (area.height - 2) : 0,
left : area.x + 1,
top : area.y + 1,
"z-index": area.z + 2
});
},
updateResizeHandlers = function (show) {
if (! options.allowResize) {
return;
}
if (show) {
$.each($resizeHandlers, function(name, $handler) {
var top,
left,
semiwidth = Math.round($handler.width() / 2),
semiheight = Math.round($handler.height() / 2),
vertical = name[0],
horizontal = name[name.length - 1];
if (vertical === "n") { // ====== North* ======
top = - semiheight;
} else if (vertical === "s") { // ====== South* ======
top = area.height - semiheight - 1;
} else { // === East & West ===
top = Math.round(area.height / 2) - semiheight - 1;
}
if (horizontal === "e") { // ====== *East ======
left = area.width - semiwidth - 1;
} else if (horizontal === "w") { // ====== *West ======
left = - semiwidth;
} else { // == North & South ==
left = Math.round(area.width / 2) - semiwidth - 1;
}
$handler.css({
display: "block",
left: area.x + left,
top: area.y + top,
"z-index": area.z + 1
});
});
} else {
$(".select-areas-resize-handler").each(function() {
$(this).css({ display: "none" });
});
}
},
updateBtDelete = function (visible) {
if ($btDelete) {
$btDelete.css({
display: visible ? "block" : "none",
left: area.x + area.width + 1,
top: area.y - $btDelete.outerHeight() - 1,
"z-index": area.z + 1
});
}
},
updateCursor = function (cursorType) {
$outline.css({
cursor: cursorType
});
$selection.css({
cursor: cursorType
});
},
refresh = function(sender) {
switch (sender) {
case "startSelection":
parent._refresh();
updateSelection();
updateResizeHandlers();
updateBtDelete(true);
break;
case "pickSelection":
case "pickResizeHandler":
updateResizeHandlers();
break;
case "resizeSelection":
updateSelection();
updateResizeHandlers();
updateCursor("crosshair");
updateBtDelete(true);
break;
case "moveSelection":
updateSelection();
updateResizeHandlers();
updateCursor("move");
updateBtDelete(true);
break;
case "blur":
updateSelection();
updateResizeHandlers();
updateBtDelete();
break;
//case "releaseSelection":
default:
updateSelection();
updateResizeHandlers(true);
updateBtDelete(true);
}
},
startSelection = function (event) {
cancelEvent(event);
// Reset the selection size
area.width = options.minSize[0];
area.height = options.minSize[1];
focus();
on("move", resizeSelection);
on("stop", releaseSelection);
// Get the selection origin
selectionOrigin = getMousePosition(event);
if (selectionOrigin[0] + area.width > $image.width()) {
selectionOrigin[0] = $image.width() - area.width;
}
if (selectionOrigin[1] + area.height > $image.height()) {
selectionOrigin[1] = $image.height() - area.height;
}
// And set its position
area.x = selectionOrigin[0];
area.y = selectionOrigin[1];
refresh("startSelection");
},
pickSelection = function (event) {
cancelEvent(event);
focus();
on("move", moveSelection);
on("stop", releaseSelection);
var mousePosition = getMousePosition(event);
// Get the selection offset relative to the mouse position
selectionOffset[0] = mousePosition[0] - area.x;
selectionOffset[1] = mousePosition[1] - area.y;
refresh("pickSelection");
},
pickResizeHandler = function (event) {
cancelEvent(event);
focus();
var card = event.target.className.split(" ")[1];
if (card[card.length - 1] === "w") {
selectionOrigin[0] += area.width;
area.x = selectionOrigin[0] - area.width;
}
if (card[0] === "n") {
selectionOrigin[1] += area.height;
area.y = selectionOrigin[1] - area.height;
}
if (card === "n" || card === "s") {
resizeHorizontally = false;
} else if (card === "e" || card === "w") {
resizeVertically = false;
}
on("move", resizeSelection);
on("stop", releaseSelection);
refresh("pickResizeHandler");
},
resizeSelection = function (event) {
cancelEvent(event);
focus();
var mousePosition = getMousePosition(event);
// Get the selection size
var height = mousePosition[1] - selectionOrigin[1],
width = mousePosition[0] - selectionOrigin[0];
// If the selection size is smaller than the minimum size set it to minimum size
if (Math.abs(width) < options.minSize[0]) {
width = (width >= 0) ? options.minSize[0] : - options.minSize[0];
}
if (Math.abs(height) < options.minSize[1]) {
height = (height >= 0) ? options.minSize[1] : - options.minSize[1];
}
// Test if the selection size exceeds the image bounds
if (selectionOrigin[0] + width < 0 || selectionOrigin[0] + width > $image.width()) {
width = - width;
}
if (selectionOrigin[1] + height < 0 || selectionOrigin[1] + height > $image.height()) {
height = - height;
}
// Test if the selection size is bigger than the maximum size (ignored if minSize > maxSize)
if (options.maxSize[0] > options.minSize[0] && options.maxSize[1] > options.minSize[1]) {
if (Math.abs(width) > options.maxSize[0]) {
width = (width >= 0) ? options.maxSize[0] : - options.maxSize[0];
}
if (Math.abs(height) > options.maxSize[1]) {
height = (height >= 0) ? options.maxSize[1] : - options.maxSize[1];
}
}
// Set the selection size
if (resizeHorizontally) {
area.width = width;
}
if (resizeVertically) {
area.height = height;
}
// If any aspect ratio is specified
if (options.aspectRatio) {
// Calculate the new width and height
if ((width > 0 && height > 0) || (width < 0 && height < 0)) {
if (resizeHorizontally) {
height = Math.round(width / options.aspectRatio);
} else {
width = Math.round(height * options.aspectRatio);
}
} else {
if (resizeHorizontally) {
height = - Math.round(width / options.aspectRatio);
} else {
width = - Math.round(height * options.aspectRatio);
}
}
// Test if the new size exceeds the image bounds
if (selectionOrigin[0] + width > $image.width()) {
width = $image.width() - selectionOrigin[0];
height = (height > 0) ? Math.round(width / options.aspectRatio) : - Math.round(width / options.aspectRatio);
}
if (selectionOrigin[1] + height < 0) {
height = - selectionOrigin[1];
width = (width > 0) ? - Math.round(height * options.aspectRatio) : Math.round(height * options.aspectRatio);
}
if (selectionOrigin[1] + height > $image.height()) {
height = $image.height() - selectionOrigin[1];
width = (width > 0) ? Math.round(height * options.aspectRatio) : - Math.round(height * options.aspectRatio);
}
// Set the selection size
area.width = width;
area.height = height;
}
if (area.width < 0) {
area.width = Math.abs(area.width);
area.x = selectionOrigin[0] - area.width;
} else {
area.x = selectionOrigin[0];
}
if (area.height < 0) {
area.height = Math.abs(area.height);
area.y = selectionOrigin[1] - area.height;
} else {
area.y = selectionOrigin[1];
}
fireEvent("changing");
refresh("resizeSelection");
},
moveSelection = function (event) {
cancelEvent(event);
if (! options.allowMove) {
return;
}
focus();
var mousePosition = getMousePosition(event);
moveTo({
x: mousePosition[0] - selectionOffset[0],
y: mousePosition[1] - selectionOffset[1]
});
fireEvent("changing");
},
moveTo = function (point) {
// Set the selection position on the x-axis relative to the bounds
// of the image
if (point.x > 0) {
if (point.x + area.width < $image.width()) {
area.x = point.x;
} else {
area.x = $image.width() - area.width;
}
} else {
area.x = 0;
}
// Set the selection position on the y-axis relative to the bounds
// of the image
if (point.y > 0) {
if (point.y + area.height < $image.height()) {
area.y = point.y;
} else {
area.y = $image.height() - area.height;
}
} else {
area.y = 0;
}
refresh("moveSelection");
},
releaseSelection = function (event) {
cancelEvent(event);
off("move", "stop");
// Update the selection origin
selectionOrigin[0] = area.x;
selectionOrigin[1] = area.y;
// Reset the resize constraints
resizeHorizontally = true;
resizeVertically = true;
fireEvent("changed");
refresh("releaseSelection");
},
deleteSelection = function (event) {
cancelEvent(event);
$selection.remove();
$outline.remove();
$.each($resizeHandlers, function(card, $handler) {
$handler.remove();
});
$btDelete.remove();
parent._remove(id);
fireEvent("changed");
},
getElementOffset = function (object) {
var offset = $(object).offset();
return [offset.left, offset.top];
},
getMousePosition = function (event) {
var imageOffset = getElementOffset($image);
if (! event.pageX) {
if (event.originalEvent) {
event = event.originalEvent;
}
if(event.changedTouches) {
event = event.changedTouches[0];
}
if(event.touches) {
event = event.touches[0];
}
}
var x = event.pageX - imageOffset[0],
y = event.pageY - imageOffset[1];
x = (x < 0) ? 0 : (x > $image.width()) ? $image.width() : x;
y = (y < 0) ? 0 : (y > $image.height()) ? $image.height() : y;
return [x, y];
};
// Initialize an outline layer and place it above the trigger layer
$outline = $("<div class=\"select-areas-outline\" />")
.css({
opacity : options.outlineOpacity,
position : "absolute"
})
.insertAfter($trigger);
// Initialize a selection layer and place it above the outline layer
$selection = $("<div />")
.addClass("select-areas-background-area")
.css({
background : "#fff url(" + $image.attr("src") + ") no-repeat",
backgroundSize : $image.width() + "px",
position : "absolute"
})
.insertAfter($outline);
// Initialize all handlers
if (options.allowResize) {
$.each(["nw", "n", "ne", "e", "se", "s", "sw", "w"], function (key, card) {
$resizeHandlers[card] = $("<div class=\"select-areas-resize-handler " + card + "\"/>")
.css({
opacity : 0.5,
position : "absolute",
cursor : card + "-resize"
})
.insertAfter($selection)
.mousedown(pickResizeHandler)
.bind("touchstart", pickResizeHandler);
});
}
// initialize delete button
if (options.allowDelete) {
var bindToDelete = function ($obj) {
$obj.click(deleteSelection)
.bind("touchstart", deleteSelection)
.bind("tap", deleteSelection);
return $obj;
};
$btDelete = bindToDelete($("<div class=\"delete-area\" />"))
.append(bindToDelete($("<div class=\"select-areas-delete-area\" />")))
.insertAfter($selection);
}
if (options.allowMove) {
$selection.mousedown(pickSelection).bind("touchstart", pickSelection);
}
focus();
return {
getData: getData,
startSelection: startSelection,
deleteSelection: deleteSelection,
options: options,
blur: blur,
focus: focus,
nudge: function (point) {
point.x = area.x;
point.y = area.y;
if (point.d) {
point.y = area.y + point.d;
}
if (point.u) {
point.y = area.y - point.u;
}
if (point.l) {
point.x = area.x - point.l;
}
if (point.r) {
point.x = area.x + point.r;
}
moveTo(point);
fireEvent("changed");
},
set: function (dimensions, silent) {
area = $.extend(area, dimensions);
selectionOrigin[0] = area.x;
selectionOrigin[1] = area.y;
if (! silent) {
fireEvent("changed");
}
},
contains: function (point) {
return (point.x >= area.x) && (point.x <= area.x + area.width) &&
(point.y >= area.y) && (point.y <= area.y + area.height);
}
};
};
$.imageSelectAreas = function() { };
$.imageSelectAreas.prototype.init = function (object, customOptions) {
var that = this,
defaultOptions = {
allowEdit: true,
allowMove: true,
allowResize: true,
allowSelect: true,
allowDelete: true,
allowNudge: true,
aspectRatio: 0,
minSize: [0, 0],
maxSize: [0, 0],
width: 0,
maxAreas: 0,
outlineOpacity: 0.5,
overlayOpacity: 0.5,
areas: [],
onChanging: null,
onChanged: null
};
this.options = $.extend(defaultOptions, customOptions);
if (! this.options.allowEdit) {
this.options.allowSelect = this.options.allowMove = this.options.allowResize = this.options.allowDelete = false;
}
this._areas = {};
// Initialize the image layer
this.$image = $(object);
this.ratio = 1;
if (this.options.width && this.$image.width() && this.options.width !== this.$image.width()) {
this.ratio = this.options.width / this.$image.width();
this.$image.width(this.options.width);
}
if (this.options.onChanging) {
this.$image.on("changing", this.options.onChanging);
}
if (this.options.onChanged) {
this.$image.on("changed", this.options.onChanged);
}
if (this.options.onLoaded) {
this.$image.on("loaded", this.options.onLoaded);
}
// Initialize an image holder
this.$holder = $("<div />")
.css({
position : "relative",
width: this.$image.width(),
height: this.$image.height()
});
// Wrap the holder around the image
this.$image.wrap(this.$holder)
.css({
position : "absolute"
});
// Initialize an overlay layer and place it above the image
this.$overlay = $("<div class=\"select-areas-overlay\" />")
.css({
opacity : this.options.overlayOpacity,
position : "absolute",
width: this.$image.width(),
height: this.$image.height()
})
.insertAfter(this.$image);
// Initialize a trigger layer and place it above the overlay layer
this.$trigger = $("<div />")
.css({
backgroundColor : "#000000",
opacity : 0,
position : "absolute",
width: this.$image.width(),
height: this.$image.height()
})
.insertAfter(this.$overlay);
$.each(this.options.areas, function (key, area) {
that._add(area, true);
});
this.blurAll();
this._refresh();
if (this.options.allowSelect) {
// Bind an event handler to the "mousedown" event of the trigger layer
this.$trigger.mousedown($.proxy(this.newArea, this)).on("touchstart", $.proxy(this.newArea, this));
}
if (this.options.allowNudge) {
$('html').keydown(function (e) { // move selection with arrow keys
var codes = {
37: "l",
38: "u",
39: "r",
40: "d"
},
direction = codes[e.which],
selectedArea;
if (direction) {
that._eachArea(function (area) {
if (area.getData().z === 100) {
selectedArea = area;
return false;
}
});
if (selectedArea) {
var move = {};
move[direction] = 1;
selectedArea.nudge(move);
}
}
});
}
};
$.imageSelectAreas.prototype._refresh = function () {
var nbAreas = this.areas().length;
this.$overlay.css({
display : nbAreas? "block" : "none"
});
if (nbAreas) {
this.$image.addClass("blurred");
} else {
this.$image.removeClass("blurred");
}
this.$trigger.css({
cursor : this.options.allowSelect ? "crosshair" : "default"
});
};
$.imageSelectAreas.prototype._eachArea = function (cb) {
$.each(this._areas, function (id, area) {
if (area) {
return cb(area, id);
}
});
};
$.imageSelectAreas.prototype._remove = function (id) {
delete this._areas[id];
this._refresh();
};
$.imageSelectAreas.prototype.remove = function (id) {
if (this._areas[id]) {
this._areas[id].deleteSelection();
}
};
$.imageSelectAreas.prototype.newArea = function (event) {
var id = -1;
this.blurAll();
if (this.options.maxAreas && this.options.maxAreas <= this.areas().length) {
return id;
}
this._eachArea(function (area, index) {
id = Math.max(id, parseInt(index, 10));
});
id += 1;
this._areas[id] = $.imageArea(this, id);
if (event) {
this._areas[id].startSelection(event);
}
return id;
};
$.imageSelectAreas.prototype.set = function (id, options, silent) {
if (this._areas[id]) {
options.id = id;
this._areas[id].set(options, silent);
this._areas[id].focus();
}
};
$.imageSelectAreas.prototype._add = function (options, silent) {
var id = this.newArea();
this.set(id, options, silent);
};
$.imageSelectAreas.prototype.add = function (options) {
var that = this;
this.blurAll();
if ($.isArray(options)) {
$.each(options, function (key, val) {
that._add(val);
});
} else {
this._add(options);
}
this._refresh();
if (! this.options.allowSelect && ! this.options.allowMove && ! this.options.allowResize && ! this.options.allowDelete) {
this.blurAll();
}
};
$.imageSelectAreas.prototype.reset = function () {
var that = this;
this._eachArea(function (area, id) {
that.remove(id);
});
this._refresh();
};
$.imageSelectAreas.prototype.destroy = function () {
this.reset();
this.$holder.remove();
this.$overlay.remove();
this.$trigger.remove();
this.$image.css("width", "").css("position", "").unwrap();
this.$image.removeData("mainImageSelectAreas");
};
$.imageSelectAreas.prototype.areas = function () {
var ret = [];
this._eachArea(function (area) {
ret.push(area.getData());
});
return ret;
};
$.imageSelectAreas.prototype.relativeAreas = function () {
var areas = this.areas(),
ret = [],
ratio = this.ratio,
scale = function (val) {
return Math.floor(val / ratio);
};
for (var i = 0; i < areas.length; i++) {
ret[i] = $.extend({}, areas[i]);
ret[i].x = scale(ret[i].x);
ret[i].y = scale(ret[i].y);
ret[i].width = scale(ret[i].width);
ret[i].height = scale(ret[i].height);
}
return ret;
};
$.imageSelectAreas.prototype.blurAll = function () {
this._eachArea(function (area) {
area.blur();
});
};
$.imageSelectAreas.prototype.contains = function (point) {
var res = false;
this._eachArea(function (area) {
if (area.contains(point)) {
res = true;
return false;
}
});
return res;
};
$.selectAreas = function(object, options) {
var $object = $(object);
if (! $object.data("mainImageSelectAreas")) {
var mainImageSelectAreas = new $.imageSelectAreas();
mainImageSelectAreas.init(object, options);
$object.data("mainImageSelectAreas", mainImageSelectAreas);
$object.trigger("loaded");
}
return $object.data("mainImageSelectAreas");
};
$.fn.selectAreas = function(customOptions) {
if ( $.imageSelectAreas.prototype[customOptions] ) { // Method call
var ret = $.imageSelectAreas.prototype[ customOptions ].apply( $.selectAreas(this), Array.prototype.slice.call( arguments, 1 ));
return typeof ret === "undefined" ? this : ret;
} else if ( typeof customOptions === "object" || ! customOptions ) { // Initialization
//Iterate over each object
this.each(function() {
var currentObject = this,
image = new Image();
// And attach selectAreas when the object is loaded
image.onload = function() {
$.selectAreas(currentObject, customOptions);
};
// Reset the src because cached images don"t fire load sometimes
image.src = currentObject.src;
});
return this;
} else {
$.error( "Method " + customOptions + " does not exist on jQuery.selectAreas" );
}
};
}) (jQuery);
...@@ -30,11 +30,23 @@ var config = { ...@@ -30,11 +30,23 @@ var config = {
'popupWindow': 'mage/popup-window', 'popupWindow': 'mage/popup-window',
'validation': 'mage/validation/validation', 'validation': 'mage/validation/validation',
'welcome': 'Magento_Theme/js/view/welcome', 'welcome': 'Magento_Theme/js/view/welcome',
'breadcrumbs': 'Magento_Theme/js/view/breadcrumbs' 'breadcrumbs': 'Magento_Theme/js/view/breadcrumbs',
// 'selectareas': 'jquery/selectareas'
} }
}, },
paths: { paths: {
'jquery/ui': 'jquery/jquery-ui' 'jquery/ui': 'jquery/jquery-ui',
'selectareas': 'jquery/selectareas',
'Croppie': 'jquery/croppie'
},
shim: {
'selectareas': {
deps: ['jquery']
},
'Croppie': {
deps: ['jquery']
}
}, },
deps: [ deps: [
'jquery/jquery.mobile.custom', 'jquery/jquery.mobile.custom',
...@@ -890,42 +902,42 @@ var config = { ...@@ -890,42 +902,42 @@ var config = {
require.config(config); require.config(config);
})(); })();
(function() { (function() {
var config = { var config = {
map: { map: {
'*': { '*': {
customModal: 'Sm_CartQuickPro/js/custom-modal', customModal: 'Sm_CartQuickPro/js/custom-modal',
quickView: 'Sm_CartQuickPro/js/custom-quickview', quickView: 'Sm_CartQuickPro/js/custom-quickview',
ajaxCart: 'Sm_CartQuickPro/js/custom-addtocart', ajaxCart: 'Sm_CartQuickPro/js/custom-addtocart',
addToCart: 'Sm_CartQuickPro/js/custom-msrp', addToCart: 'Sm_CartQuickPro/js/custom-msrp',
sidebar: 'Sm_CartQuickPro/js/custom-sidebar', sidebar: 'Sm_CartQuickPro/js/custom-sidebar',
compareItems: 'Sm_CartQuickPro/js/custom-compare', compareItems: 'Sm_CartQuickPro/js/custom-compare',
wishlist: 'Sm_CartQuickPro/js/custom-wishlist' wishlist: 'Sm_CartQuickPro/js/custom-wishlist'
} }
}, },
deps: [ deps: [
'Magento_Catalog/js/catalog-add-to-cart', 'Magento_Catalog/js/catalog-add-to-cart',
'Magento_Msrp/js/msrp' 'Magento_Msrp/js/msrp'
] ]
}; };
require.config(config); require.config(config);
})(); })();
(function() { (function() {
var config = { var config = {
map: { map: {
'*': { '*': {
jquerybootstrap: "Sm_Shop4u/js/bootstrap/bootstrap.min", jquerybootstrap: "Sm_Shop4u/js/bootstrap/bootstrap.min",
owlcarousel: "Sm_Shop4u/js/owl.carousel", owlcarousel: "Sm_Shop4u/js/owl.carousel",
jqueryfancyboxpack: "Sm_Shop4u/js/jquery.fancybox.pack", jqueryfancyboxpack: "Sm_Shop4u/js/jquery.fancybox.pack",
fancybuttons: "Sm_Shop4u/js/helpers/jquery.fancybox-buttons", fancybuttons: "Sm_Shop4u/js/helpers/jquery.fancybox-buttons",
fancymedia: "Sm_Shop4u/js/helpers/jquery.fancybox-media", fancymedia: "Sm_Shop4u/js/helpers/jquery.fancybox-media",
fancythumbs: "Sm_Shop4u/js/helpers/jquery.fancybox-thumbs", fancythumbs: "Sm_Shop4u/js/helpers/jquery.fancybox-thumbs",
jqueryunveil: "Sm_Shop4u/js/jquery.unveil", jqueryunveil: "Sm_Shop4u/js/jquery.unveil",
yttheme: "Sm_Shop4u/js/yttheme" yttheme: "Sm_Shop4u/js/yttheme"
} }
} }
}; };
require.config(config); require.config(config);
})(); })();
...@@ -950,4 +962,4 @@ require.config(config); ...@@ -950,4 +962,4 @@ require.config(config);
})(require); })(require);
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment