croppic.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /*
  2. * CROPPIC
  3. * dependancy: jQuery
  4. * author: Ognjen "Zmaj Džedaj" Božičković and Mat Steinlin
  5. */
  6. (function (window, document) {
  7. Croppic = function (id, options) {
  8. var that = this;
  9. that.id = id;
  10. that.obj = $('#' + id);
  11. that.outputDiv = that.obj;
  12. that.imgUrl="";
  13. that.saveImgUrl="";
  14. that.imgBackground="";
  15. // DEFAULT OPTIONS
  16. that.options = {
  17. uploadUrl:'',
  18. uploadData:{},
  19. cropUrl:'',
  20. cropData:{},
  21. outputUrlId:'',
  22. //styles
  23. imgEyecandy:true,
  24. imgEyecandyOpacity:0.2,
  25. initialZoom:40,
  26. zoomFactor:10,
  27. rotateFactor:5,
  28. doubleZoomControls:true,
  29. rotateControls: true,
  30. modal:false,
  31. customUploadButtonId:'',
  32. customSaveButtonId:'',
  33. loaderHtml:'',
  34. scaleToFill: true,
  35. processInline: false,
  36. loadPicture:'',
  37. onReset: null,
  38. enableMousescroll: false,
  39. colorAbsorption:false,
  40. //callbacks
  41. onBeforeImgUpload: null,
  42. onAfterImgUpload: null,
  43. onImgDrag: null,
  44. onImgZoom: null,
  45. onImgRotate: null,
  46. onBeforeImgCrop: null,
  47. onAfterImgCrop: null,
  48. onBeforeRemoveCroppedImg: null,
  49. onAfterRemoveCroppedImg: null,
  50. onError: null,
  51. };
  52. // OVERWRITE DEFAULT OPTIONS
  53. for (i in options) that.options[i] = options[i];
  54. // INIT THE WHOLE DAMN THING!!!
  55. that.init();
  56. };
  57. Croppic.prototype = {
  58. id:'',
  59. imgInitW:0,
  60. imgInitH:0,
  61. imgW:0,
  62. imgH:0,
  63. actualRotationImgW:0,
  64. actualRotationImgH:0,
  65. objW:0,
  66. objH:0,
  67. actualRotation: 0,
  68. windowW:0,
  69. windowH:$(window).height(),
  70. obj:{},
  71. outputDiv:{},
  72. outputUrlObj:{},
  73. img:{},
  74. defaultImg:{},
  75. croppedImg:{},
  76. imgEyecandy:{},
  77. form:{},
  78. iframeform: {},
  79. iframeobj: {},
  80. cropControlsUpload:{},
  81. cropControlsCrop:{},
  82. cropControlZoomMuchIn:{},
  83. cropControlZoomMuchOut:{},
  84. cropControlZoomIn:{},
  85. cropControlZoomOut:{},
  86. cropControlCrop:{},
  87. cropControlReset:{},
  88. cropControlRemoveCroppedImage:{},
  89. cropControlOriginal:{},
  90. modal:{},
  91. loader:{},
  92. cropSaveControl:{},
  93. init: function () {
  94. var that = this;
  95. that.objW = that.obj.width();
  96. that.objH = that.obj.height();
  97. // reset rotation
  98. that.actualRotation = 0;
  99. that.actualRotationImgH=0;
  100. that.actualRotationImgW=0;
  101. that.colorAbsorption=false;
  102. that.imgBackground="";
  103. if( $.isEmptyObject(that.defaultImg)){ that.defaultImg = that.obj.find('img'); }
  104. that.createImgUploadControls();
  105. if( $.isEmptyObject(that.options.loadPicture)){
  106. that.bindImgUploadControl();
  107. }else{
  108. that.loadExistingImage();
  109. }
  110. },
  111. createImgUploadControls: function(){
  112. var that = this;
  113. var cropControlUpload = '';
  114. if(that.options.customUploadButtonId ===''){ cropControlUpload = '<i class="cropControlUpload"></i>'; }
  115. var cropControlRemoveCroppedImage = '<i class="cropControlRemoveCroppedImage"></i>';
  116. var cropControlOriginal = '<i class="cropControlOriginal"></i>';
  117. if( $.isEmptyObject(that.croppedImg))
  118. {
  119. cropControlRemoveCroppedImage='';
  120. cropControlOriginal='';
  121. }
  122. if( !$.isEmptyObject(that.options.loadPicture)){ cropControlUpload='';}
  123. var html = '<div class="cropControls cropControlsUpload"> ' + cropControlUpload + cropControlOriginal + cropControlRemoveCroppedImage + ' </div>';
  124. that.outputDiv.append(html);
  125. that.cropControlsUpload = that.outputDiv.find('.cropControlsUpload');
  126. if(that.options.customUploadButtonId ===''){ that.imgUploadControl = that.outputDiv.find('.cropControlUpload'); }
  127. else{ that.imgUploadControl = $('#'+that.options.customUploadButtonId); that.imgUploadControl.show(); }
  128. if(that.options.customSaveButtonId !==''){
  129. that.cropSaveControl= $('#'+that.options.customSaveButtonId); that.cropSaveControl.hide();
  130. }
  131. if( !$.isEmptyObject(that.croppedImg)){
  132. that.cropControlRemoveCroppedImage = that.outputDiv.find('.cropControlRemoveCroppedImage');
  133. that.cropControlOriginal = that.outputDiv.find('.cropControlOriginal');
  134. }
  135. },
  136. bindImgUploadControl: function(){
  137. var that = this;
  138. // CREATE UPLOAD IMG FORM
  139. var formHtml = '<form class="' + that.id + '_imgUploadForm" style="visibility: hidden;"> <input type="file" name="img" id="' + that.id + '_imgUploadField"> </form>';
  140. that.outputDiv.append(formHtml);
  141. that.form = that.outputDiv.find('.'+that.id+'_imgUploadForm');
  142. // CREATE FALLBACK IE9 IFRAME
  143. var fileUploadId = that.CreateFallbackIframe();
  144. that.imgUploadControl.off('click');
  145. that.imgUploadControl.on('click',function(){
  146. if (fileUploadId === "") {
  147. that.form.find('input[type="file"]').trigger('click');
  148. } else {
  149. //Trigger iframe file input click, otherwise access restriction error
  150. that.iframeform.find('input[type="file"]').trigger('click');
  151. }
  152. });
  153. that.cropSaveControl.off('click');
  154. that.cropSaveControl.on('click',function(){
  155. // var res = confirm('您确定要使用编辑好的图片吗?\n\r' +
  156. // '[确认]使用图片\n\r' +
  157. // '[取消]继续编辑');
  158. // if (res) {
  159. // that.destroy();
  160. // window.location.href="https://wwww.croppic.com?"+that.saveImgUrl;
  161. // }
  162. that.destroy();
  163. window.location.href="https://wwww.croppic.com?"+that.saveImgUrl;
  164. });
  165. if( !$.isEmptyObject(that.croppedImg)){
  166. that.cropControlRemoveCroppedImage.on('click',function(){
  167. if (typeof (that.options.onBeforeRemoveCroppedImg) === typeof(Function)) {
  168. that.options.onBeforeRemoveCroppedImg.call(that);
  169. }
  170. var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
  171. '[确认]使用当前图片\n\r' +
  172. '[取消]重新选择图片');
  173. var width= that.imgInitW;
  174. var height= that.imgInitH;
  175. that.croppedImg.remove();
  176. that.croppedImg = {};
  177. $(this).hide();
  178. that.cropSaveControl.hide();
  179. that.cropControlOriginal.hide();
  180. if (typeof (that.options.onAfterRemoveCroppedImg) === typeof(Function)) {
  181. that.options.onAfterRemoveCroppedImg.call(that);
  182. }
  183. if( !$.isEmptyObject(that.defaultImg)){
  184. that.obj.append(that.defaultImg);
  185. }
  186. if(that.options.outputUrlId !== ''){ $('#'+that.options.outputUrlId).val(''); }
  187. that.imgUploadControl.show();
  188. if (res) {
  189. that.showLoader();
  190. that.imgUploadControl.hide();
  191. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  192. that.imgInitW = that.imgW = width;
  193. that.imgInitH = that.imgH = height;
  194. that.saveImgUrl="";
  195. that.obj.append('<img src="'+that.imgUrl+'">');
  196. that.initCropper();
  197. that.hideLoader();
  198. }
  199. });
  200. that.cropControlOriginal.on('click',function(){
  201. if (that.imgUrl=='')
  202. {
  203. alert('请选择图片' );
  204. return;
  205. }
  206. var res = confirm('您确定要使用原图吗?\n\r' +
  207. '[确认]使用原图\n\r' +
  208. '[取消]继续编辑');
  209. if (res) {
  210. that.destroy();
  211. window.location.href="https://wwww.croppic.com?"+that.imgUrl;
  212. }
  213. });
  214. }
  215. that.form.find('input[type="file"]').change(function(){
  216. if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
  217. that.showLoader();
  218. that.imgUploadControl.hide();
  219. if(that.options.processInline){
  220. // Checking Browser Support for FileReader API
  221. if (typeof FileReader == "undefined"){
  222. if (that.options.onError) that.options.onError.call(that,"processInline is not supported by your Browser");
  223. that.reset();
  224. }else{
  225. var filePath=that.form.find('input[type="file"]')[0].files[0];
  226. if( !$.isEmptyObject(that.croppedImg)){
  227. that.destroy();
  228. }
  229. var reader = new FileReader();
  230. reader.onload = function (e) {
  231. var image = new Image();
  232. image.src = e.target.result;
  233. image.onload = function(){
  234. that.imgInitW = that.imgW = image.width;
  235. that.imgInitH = that.imgH = image.height;
  236. if(that.options.modal){ that.createModal(); }
  237. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  238. that.imgUrl=image.src;
  239. that.saveImgUrl="";
  240. that.obj.append('<img src="'+image.src+'">');
  241. that.initCropper();
  242. that.hideLoader();
  243. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  244. }
  245. };
  246. reader.readAsDataURL(filePath);
  247. }
  248. } else {
  249. try {
  250. // other modern browsers
  251. formData = new FormData(that.form[0]);
  252. } catch(e) {
  253. // IE10 MUST have all form items appended as individual form key / value pairs
  254. formData = new FormData();
  255. formData.append('img', that.form.find("input[type=file]")[0].files[0]);
  256. }
  257. for (var key in that.options.uploadData) {
  258. if( that.options.uploadData.hasOwnProperty(key) ) {
  259. formData.append( key , that.options.uploadData[key] );
  260. }
  261. }
  262. $.ajax({
  263. url: that.options.uploadUrl,
  264. data: formData,
  265. context: document.body,
  266. cache: false,
  267. contentType: false,
  268. processData: false,
  269. type: 'POST'
  270. }).always(function (data) {
  271. that.afterUpload(data);
  272. });
  273. }
  274. });
  275. },
  276. loadExistingImage: function(){
  277. var that = this;
  278. if( $.isEmptyObject(that.croppedImg)){
  279. if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
  280. that.showLoader();
  281. if(that.options.modal){ that.createModal(); }
  282. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  283. that.imgUrl=that.options.loadPicture ;
  284. var img =$('<img src="'+ that.options.loadPicture +'">');
  285. that.obj.append(img);
  286. img.load(function() {
  287. that.imgInitW = that.imgW = this.width;
  288. that.imgInitH = that.imgH = this.height;
  289. that.initCropper();
  290. that.hideLoader();
  291. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  292. });
  293. }else{
  294. that.cropControlRemoveCroppedImage.on('click',function(){
  295. var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
  296. '[确认]使用当前图片\n\r' +
  297. '[取消]重新选择图片');
  298. var width= that.imgInitW;
  299. var height= that.imgInitH;
  300. that.croppedImg.remove();
  301. $(this).hide();
  302. that.cropSaveControl.hide();
  303. that.cropControlOriginal.hide();
  304. if( !$.isEmptyObject(that.defaultImg)){
  305. that.obj.append(that.defaultImg);
  306. }
  307. if(that.options.outputUrlId !== ''){ $('#'+that.options.outputUrlId).val(''); }
  308. that.croppedImg = '';
  309. that.reset();
  310. if (res) {
  311. that.showLoader();
  312. that.imgUploadControl.hide();
  313. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  314. that.imgInitW = that.imgW = width;
  315. that.imgInitH = that.imgH = height;
  316. that.saveImgUrl="";
  317. that.obj.append('<img src="'+that.imgUrl+'">');
  318. that.initCropper();
  319. that.hideLoader();
  320. }
  321. });
  322. }
  323. },
  324. afterUpload: function(data){
  325. var that = this;
  326. response = typeof data =='object' ? data : jQuery.parseJSON(data);
  327. if (response.status == 'success') {
  328. that.imgInitW = that.imgW = response.width;
  329. that.imgInitH = that.imgH = response.height;
  330. if (that.options.modal) { that.createModal(); }
  331. if (!$.isEmptyObject(that.croppedImg)) { that.croppedImg.remove(); }
  332. that.imgUrl = response.url;
  333. var img = $('<img src="'+response.url+'">')
  334. that.obj.append(img);
  335. img.load(function(){
  336. that.initCropper();
  337. that.hideLoader();
  338. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  339. });
  340. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  341. }
  342. if (response.status == 'error') {
  343. alert(response.message);
  344. if (that.options.onError) that.options.onError.call(that,response.message);
  345. that.hideLoader();
  346. // setTimeout( function(){ that.reset(); },2000)
  347. }
  348. },
  349. createModal: function(){
  350. var that = this;
  351. var marginTop = that.windowH/2-that.objH/2;
  352. var modalHTML = '<div id="croppicModal">'+'<div id="croppicModalObj" style="width:'+ that.objW +'px; height:'+ that.objH +'px; margin:0 auto; margin-top:'+ marginTop +'px; position: relative;"> </div>'+'</div>';
  353. $('body').append(modalHTML);
  354. that.modal = $('#croppicModal');
  355. that.obj = $('#croppicModalObj');
  356. },
  357. destroyModal: function(){
  358. var that = this;
  359. that.obj = that.outputDiv;
  360. that.modal.remove();
  361. that.modal = {};
  362. },
  363. initCropper: function(){
  364. var that = this;
  365. /*SET UP SOME VARS*/
  366. that.img = that.obj.find('img');
  367. that.img.wrap('<div class="cropImgWrapper" style="overflow:hidden; z-index:1; position:absolute; width:'+that.objW+'px; height:'+that.objH+'px;"></div>');
  368. /*INIT DRAGGING*/
  369. that.createCropControls();
  370. if(that.options.imgEyecandy){ that.createEyecandy(); }
  371. that.initDrag();
  372. that.initialScaleImg();
  373. },
  374. createEyecandy: function(){
  375. var that = this;
  376. that.imgEyecandy = that.img.clone();
  377. that.imgEyecandy.css({'z-index':'0','opacity':that.options.imgEyecandyOpacity}).appendTo(that.obj);
  378. },
  379. destroyEyecandy: function(){
  380. var that = this;
  381. that.imgEyecandy.remove();
  382. },
  383. initialScaleImg:function(){
  384. var that = this;
  385. that.zoom(0);
  386. that.zoom(that.options.initialZoom);
  387. // Adding mousewheel zoom capabilities
  388. if (that.options.enableMousescroll){
  389. that.img.on('mousewheel', function(event) {
  390. event.preventDefault();
  391. if (that.colorAbsorption)
  392. {
  393. return;
  394. }
  395. that.zoom(that.options.zoomFactor*event.deltaY);
  396. });
  397. }
  398. // initial center image
  399. that.img.css({'left': -(that.imgW -that.objW)/2, 'top': -(that.imgH -that.objH)/2, 'position':'relative'});
  400. if(that.options.imgEyecandy){ that.imgEyecandy.css({'left': -(that.imgW -that.objW)/2, 'top': -(that.imgH -that.objH)/2, 'position':'relative'}); }
  401. },
  402. createCropControls: function(){
  403. var that = this;
  404. // CREATE CONTROLS
  405. var cropControlZoomMuchIn = '';
  406. var cropControlZoomIn = '<i class="cropControlZoomIn"></i>';
  407. var cropControlZoomOut = '<i class="cropControlZoomOut"></i>';
  408. var cropControlZoomMuchOut = '';
  409. var cropControlRotateLeft = '';
  410. var cropControlRotateRight = '';
  411. var cropControlRotateMuchLeft = '';
  412. var cropControlRotateMuchRight = '';
  413. var cropControlCrop = '<i class="cropControlCrop"></i>';
  414. var cropControlReset = '<i class="cropControlReset"></i>';
  415. var cropControlOriginal = '<i class="cropControlOriginal"></i>';
  416. var cropControlXiColor = '<i class="cropControlXiColor"></i>';
  417. var cropControlXiColor2 = '<i class="cropControlXiColor2"></i>';
  418. var cropControlSetColor = '<i class="cropControlSetColor"></i>';
  419. var html;
  420. if(that.options.doubleZoomControls){
  421. cropControlZoomMuchIn = '<i class="cropControlZoomMuchIn"></i>';
  422. cropControlZoomMuchOut = '<i class="cropControlZoomMuchOut"></i>';
  423. }
  424. if(that.options.rotateControls){
  425. cropControlRotateLeft = '<i class="cropControlRotateLeft"></i>';
  426. cropControlRotateRight = '<i class="cropControlRotateRight"></i>';
  427. cropControlRotateMuchLeft = '<i class="cropControlRotateMuchLeft"></i>';
  428. cropControlRotateMuchRight = '<i class="cropControlRotateMuchRight"></i>';
  429. }
  430. html = '<div class="cropControls cropControlsCrop">'+ cropControlZoomMuchIn + cropControlZoomIn + cropControlZoomOut + cropControlZoomMuchOut
  431. + cropControlRotateMuchLeft+ cropControlRotateLeft + cropControlRotateRight + cropControlRotateMuchRight + cropControlCrop + '</div>';
  432. that.obj.append(html);
  433. html = '<div class="cropControls cropControlsCrop cropControlsUpload">' + cropControlXiColor2 + cropControlXiColor+ cropControlSetColor + cropControlOriginal + cropControlReset + '</div>';
  434. that.obj.append(html);
  435. that.cropControlsCrop = that.obj.find('.cropControlsCrop');
  436. // CACHE AND BIND CONTROLS
  437. if(that.options.doubleZoomControls){
  438. that.cropControlZoomMuchIn = that.cropControlsCrop.find('.cropControlZoomMuchIn');
  439. that.cropControlZoomMuchIn.on('click',function(){ that.zoom( that.options.zoomFactor*10 ); });
  440. that.cropControlZoomMuchOut = that.cropControlsCrop.find('.cropControlZoomMuchOut');
  441. that.cropControlZoomMuchOut.on('click',function(){ that.zoom(-that.options.zoomFactor*10); });
  442. }
  443. that.cropControlZoomIn = that.cropControlsCrop.find('.cropControlZoomIn');
  444. that.cropControlZoomIn.on('click',function(){ that.zoom(that.options.zoomFactor); });
  445. that.cropControlZoomOut = that.cropControlsCrop.find('.cropControlZoomOut');
  446. that.cropControlZoomOut.on('click',function(){ that.zoom(-that.options.zoomFactor); });
  447. that.cropControlRotateLeft = that.cropControlsCrop.find('.cropControlRotateLeft');
  448. that.cropControlRotateLeft.on('click', function() { that.rotate(-1);});
  449. that.cropControlRotateMuchLeft = that.cropControlsCrop.find('.cropControlRotateMuchLeft');
  450. that.cropControlRotateMuchLeft.on('click', function() { that.rotate(-10);});
  451. that.cropControlRotateRight = that.cropControlsCrop.find('.cropControlRotateRight');
  452. that.cropControlRotateRight.on('click', function() {that.rotate(1);});
  453. that.cropControlRotateMuchRight = that.cropControlsCrop.find('.cropControlRotateMuchRight');
  454. that.cropControlRotateMuchRight.on('click', function() {that.rotate(10);});
  455. that.cropControlCrop = that.cropControlsCrop.find('.cropControlCrop');
  456. that.cropControlCrop.on('click',function(){ that.crop(); });
  457. that.cropControlReset = that.cropControlsCrop.find('.cropControlReset');
  458. that.cropControlReset.on('click',function(){
  459. var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
  460. '[确认]使用当前图片\n\r' +
  461. '[取消]重新选择图片');
  462. var width= that.imgInitW;
  463. var height= that.imgInitH;
  464. that.reset();
  465. if (res) {
  466. that.showLoader();
  467. that.imgUploadControl.hide();
  468. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  469. that.imgInitW = that.imgW = width;
  470. that.imgInitH = that.imgH = height;
  471. that.saveImgUrl="";
  472. that.obj.append('<img src="'+that.imgUrl+'">');
  473. that.initCropper();
  474. that.hideLoader();
  475. }
  476. });
  477. that.cropControlOriginal = that.cropControlsCrop.find('.cropControlOriginal');
  478. that.cropControlOriginal.on('click',function(){
  479. if (that.imgUrl=='')
  480. {
  481. alert('请选择图片' );
  482. return;
  483. }
  484. var res = confirm('您确定要使用原图吗?\n\r' +
  485. '[确认]使用原图\n\r' +
  486. '[取消]继续编辑');
  487. if (res) {
  488. that.destroy();
  489. window.location.href="https://wwww.croppic.com?"+that.imgUrl;
  490. }
  491. });
  492. that.cropControlXiColor = that.cropControlsCrop.find('.cropControlXiColor');
  493. that.cropControlXiColor.on('click',function(){that.colorOnClick(false);});
  494. that.cropControlXiColor2 = that.cropControlsCrop.find('.cropControlXiColor2');
  495. that.cropControlXiColor2.on('click',function(){that.colorOnClick(false);});
  496. that.cropControlSetColor= that.cropControlsCrop.find('.cropControlSetColor');
  497. that.cropControlSetColor.on('click',function(){that.colorOnClick(true);});
  498. that.colpick=that.cropControlSetColor.colpick({
  499. onSubmit:function(hsb,hex,rgb,el) {
  500. var background="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";
  501. that.obj.find('.cropImgWrapper').css('background',background);
  502. $(el).colpickHide();
  503. that.imgBackground=background;
  504. }
  505. });
  506. },
  507. colorOnClick:function(input)
  508. {
  509. var that = this;
  510. if (that.colorAbsorption||input)
  511. {
  512. that.cropControlsCrop.find('.cropControlXiColor').css("display","block");
  513. that.cropControlsCrop.find('.cropControlXiColor2').css("display","none");
  514. that.colorAbsorption=false;
  515. }else {
  516. that.cropControlsCrop.find('.cropControlXiColor').css("display","none");
  517. that.cropControlsCrop.find('.cropControlXiColor2').css("display","block");
  518. that.colorAbsorption=true;
  519. }
  520. },
  521. initDrag:function(){
  522. var that = this;
  523. that.img.on("mousedown touchstart", function(e) {
  524. e.preventDefault(); // disable selection
  525. var pageX;
  526. var pageY;
  527. var userAgent = window.navigator.userAgent;
  528. if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/android/i) || (e.pageY && e.pageX) == undefined) {
  529. pageX = e.originalEvent.touches[0].pageX;
  530. pageY = e.originalEvent.touches[0].pageY;
  531. } else {
  532. pageX = e.pageX;
  533. pageY = e.pageY;
  534. }
  535. var z_idx = that.img.css('z-index'),
  536. drg_h = that.img.outerHeight(),
  537. drg_w = that.img.outerWidth(),
  538. pos_y = that.img.offset().top + drg_h - pageY,
  539. pos_x = that.img.offset().left + drg_w - pageX;
  540. if (that.colorAbsorption)
  541. {
  542. var imgWidth = that.img.width();
  543. var imhHeight = that.img.height();
  544. var x = that.imgInitW * parseInt(imgWidth-pos_x-that.actualRotationImgW) / imgWidth;
  545. var y = that.imgInitH * parseInt(imhHeight-pos_y-that.actualRotationImgH) / imhHeight;
  546. if (!(x<0||x>that.imgInitW||y<0||y>that.imgInitH))
  547. {
  548. var canvas = document.createElement("canvas");
  549. if (!canvas.getContext) {
  550. alert("很遗憾,您浏览器版本太老了,无法使用我们的小工具 !");
  551. return;
  552. }
  553. var ctx = canvas.getContext("2d");
  554. var newImg = new Image();
  555. newImg.onload = function(){
  556. canvas.width = newImg.width;
  557. canvas.height = newImg.height;
  558. ctx.drawImage(newImg, 0, 0);
  559. var imgData = ctx.getImageData(x, y, 1, 1);
  560. var rgb = {r:imgData.data[0],g:imgData.data[1],b:imgData.data[2]};
  561. var background="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";
  562. that.obj.find('.cropImgWrapper').css("background",background);
  563. that.imgBackground=background;
  564. that.cropControlSetColor.colpickSetColor(rgb);
  565. }
  566. newImg.src = that.imgUrl;
  567. return;
  568. }
  569. }
  570. that.img.css('z-index', 1000).on("mousemove touchmove", function(e) {
  571. if (that.colorAbsorption)
  572. {
  573. return;
  574. }
  575. var imgTop;
  576. var imgLeft;
  577. if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/android/i) || (e.pageY && e.pageX) == undefined) {
  578. imgTop = e.originalEvent.touches[0].pageY + pos_y - drg_h;
  579. imgLeft = e.originalEvent.touches[0].pageX + pos_x - drg_w;
  580. } else {
  581. imgTop = e.pageY + pos_y - drg_h;
  582. imgLeft = e.pageX + pos_x - drg_w;
  583. }
  584. that.img.offset({
  585. top:imgTop,
  586. left:imgLeft
  587. }).on("mouseup", function() {
  588. $(this).removeClass('draggable').css('z-index', z_idx);
  589. });
  590. if(that.options.imgEyecandy){ that.imgEyecandy.offset({ top:imgTop, left:imgLeft }); }
  591. var top=that.actualRotationImgH;
  592. var left=that.actualRotationImgW;
  593. // var top=0;
  594. // var left=0;
  595. if (that.objH < that.imgH+top*2) {
  596. if (parseInt(that.img.css('top')) > top) { that.img.css('top', top); if (that.options.imgEyecandy) { that.imgEyecandy.css('top', top);}}
  597. var maxTop = -( that.imgH - that.objH+top); if (parseInt(that.img.css('top')) < maxTop) { that.img.css('top', maxTop); if (that.options.imgEyecandy) { that.imgEyecandy.css('top', maxTop); }}
  598. }else{
  599. if (parseInt(that.img.css('top')) < -top) { that.img.css('top', -top); if (that.options.imgEyecandy) { that.imgEyecandy.css('top', top); }}
  600. var maxTop = that.objH - that.imgH+top; if (parseInt(that.img.css('top')) > maxTop) { that.img.css('top', maxTop);if (that.options.imgEyecandy) {that.imgEyecandy.css('top', maxTop); }}
  601. }
  602. if (that.objW < that.imgW+2*left) {
  603. if( parseInt( that.img.css('left')) > left ){ that.img.css('left',left); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', left); }}
  604. var maxLeft = -( that.imgW-that.objW+left); if( parseInt( that.img.css('left')) < maxLeft){ that.img.css('left', maxLeft); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', maxLeft); } }
  605. }else{
  606. if( parseInt( that.img.css('left')) < -left ){ that.img.css('left',-left); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', 0); }}
  607. var maxLeft = ( that.objW - that.imgW+left); if( parseInt( that.img.css('left')) > maxLeft){ that.img.css('left', maxLeft); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', maxLeft); } }
  608. }
  609. if (that.options.onImgDrag) that.options.onImgDrag.call(that);
  610. });
  611. }).on("mouseup", function() {
  612. that.img.off("mousemove");
  613. }).on("mouseout", function() {
  614. that.img.off("mousemove");
  615. });
  616. },
  617. rotate: function(x) {
  618. var that = this;
  619. that.colorOnClick(true);
  620. that.actualRotation += x;
  621. that.img.css({
  622. '-webkit-transform': 'rotate(' + that.actualRotation + 'deg)',
  623. '-moz-transform': 'rotate(' + that.actualRotation + 'deg)',
  624. 'transform': 'rotate(' + that.actualRotation + 'deg)',
  625. });
  626. if(that.options.imgEyecandy) {
  627. that.imgEyecandy.css({
  628. '-webkit-transform': 'rotate(' + that.actualRotation + 'deg)',
  629. '-moz-transform': 'rotate(' + that.actualRotation + 'deg)',
  630. 'transform': 'rotate(' + that.actualRotation + 'deg)',
  631. });
  632. }
  633. that.actualRotationImgH=0;
  634. that.actualRotationImgW=0;
  635. if (that.actualRotation!=0)
  636. {
  637. var actualRotation=that.actualRotation;
  638. if (actualRotation<0)
  639. {
  640. actualRotation=0-actualRotation;
  641. }
  642. if (actualRotation==90||actualRotation==270)
  643. {
  644. if(that.imgH>that.imgW)
  645. {
  646. that.actualRotationImgW=parseInt((that.imgH-that.imgW)/2);
  647. }else if(that.imgH<that.imgW)
  648. {
  649. that.actualRotationImgH=parseInt((that.imgW-that.imgH)/2);
  650. }
  651. }else if (actualRotation!=180&&actualRotation!=360) {
  652. if (actualRotation>180)
  653. {
  654. actualRotation=actualRotation-180;
  655. }
  656. if (actualRotation>90)
  657. {
  658. actualRotation=180-actualRotation;
  659. }
  660. var radian = Math.sin(actualRotation * Math.PI / 180);
  661. that.actualRotationImgW=parseInt(radian*(that.imgH)/2);
  662. that.actualRotationImgH=parseInt(radian*(that.imgW)/2);
  663. }
  664. }
  665. if (typeof that.options.onImgRotate == 'function')
  666. that.options.onImgRotate.call(that);
  667. },
  668. zoom :function(x){
  669. var that = this;
  670. that.colorOnClick(true);
  671. var ratio = that.imgW / that.imgH;
  672. var newWidth = that.imgW+x;
  673. var newHeight = newWidth/ratio;
  674. var doPositioning = true;
  675. if (x==0)
  676. {
  677. if( newWidth - that.objW < newHeight - that.objH ){
  678. newWidth = that.objW;
  679. newHeight = newWidth/ratio;
  680. }else{
  681. newHeight = that.objH;
  682. newWidth = ratio * newHeight;
  683. }
  684. }
  685. if( newWidth < that.objW || newHeight < that.objH){
  686. doPositioning = false;
  687. }
  688. if(!that.options.scaleToFill && (newWidth > that.imgInitW || newHeight > that.imgInitH)){
  689. doPositioning = false;
  690. }
  691. that.imgW = newWidth;
  692. that.img.width(newWidth);
  693. that.imgH = newHeight;
  694. that.img.height(newHeight);
  695. var newTop = parseInt( that.img.css('top') ) - x/2;
  696. var newLeft = parseInt( that.img.css('left') ) - x/2;
  697. that.actualRotationImgH=0;
  698. that.actualRotationImgW=0;
  699. if (that.actualRotation!=0)
  700. {
  701. var actualRotation=that.actualRotation;
  702. if (actualRotation<0)
  703. {
  704. actualRotation=0-actualRotation;
  705. }
  706. if (actualRotation==90||actualRotation==270)
  707. {
  708. if(that.imgH>that.imgW)
  709. {
  710. that.actualRotationImgW=parseInt((that.imgH-that.imgW)/2);
  711. }else if(that.imgH<that.imgW)
  712. {
  713. that.actualRotationImgH=parseInt((that.imgW-that.imgH)/2);
  714. }
  715. }else if (actualRotation!=180&&actualRotation!=360) {
  716. if (actualRotation>180)
  717. {
  718. actualRotation=actualRotation-180;
  719. }
  720. if (actualRotation>90)
  721. {
  722. actualRotation=180-actualRotation;
  723. }
  724. var radian = Math.sin(actualRotation * Math.PI / 180);
  725. that.actualRotationImgW=parseInt(radian*(that.imgH)/2);
  726. that.actualRotationImgH=parseInt(radian*(that.imgW)/2);
  727. }
  728. }
  729. if( newTop>-that.actualRotationImgH ){ newTop=-that.actualRotationImgH;}
  730. if( newLeft>-that.actualRotationImgW ){ newLeft=-that.actualRotationImgW;}
  731. var maxTop = -( newHeight-that.objH+that.actualRotationImgH); if( newTop < maxTop){ newTop = maxTop; }
  732. var maxLeft = -( newWidth-that.objW+that.actualRotationImgW); if( newLeft < maxLeft){ newLeft = maxLeft; }
  733. if( doPositioning ){
  734. that.img.css({'top':newTop, 'left':newLeft});
  735. }
  736. if(that.options.imgEyecandy){
  737. that.imgEyecandy.width(newWidth);
  738. that.imgEyecandy.height(newHeight);
  739. if( doPositioning ){
  740. that.imgEyecandy.css({'top':newTop, 'left':newLeft});
  741. }
  742. }
  743. if (that.options.onImgZoom) that.options.onImgZoom.call(that);
  744. },
  745. crop:function(){
  746. var that = this;
  747. that.colorOnClick(true);
  748. if (that.options.onBeforeImgCrop) that.options.onBeforeImgCrop.call(that);
  749. that.cropControlsCrop.hide();
  750. that.showLoader();
  751. var cropData = {
  752. imgUrl:that.imgUrl,
  753. imgInitW:that.imgInitW,
  754. imgInitH:that.imgInitH,
  755. imgW:that.imgW,
  756. imgH:that.imgH,
  757. imgY1:parseInt( that.img.css('top') ),
  758. imgX1: parseInt( that.img.css('left')),
  759. cropH:that.objH,
  760. cropW:that.objW,
  761. rotation:that.actualRotation,
  762. imgBackground:that.imgBackground
  763. };
  764. var formData;
  765. if(typeof FormData == 'undefined'){
  766. var XHR = new XMLHttpRequest();
  767. var urlEncodedData = "";
  768. var urlEncodedDataPairs = [];
  769. for(var key in cropData) {
  770. urlEncodedDataPairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(cropData[key]));
  771. }
  772. for(var key in that.options.cropData) {
  773. urlEncodedDataPairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(that.options.cropData[key]));
  774. }
  775. urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
  776. XHR.addEventListener('error', function(event) {
  777. if (that.options.onError) that.options.onError.call(that,"XHR Request failed");
  778. });
  779. XHR.onreadystatechange=function(){
  780. if (XHR.readyState==4 && XHR.status==200)
  781. {
  782. that.afterCrop(XHR.responseText);
  783. }
  784. }
  785. XHR.open('POST', that.options.cropUrl);
  786. XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  787. XHR.setRequestHeader('Content-Length', urlEncodedData.length);
  788. XHR.send(urlEncodedData);
  789. }else{
  790. formData = new FormData();
  791. for (var key in cropData) {
  792. if( cropData.hasOwnProperty(key) ) {
  793. formData.append( key , cropData[key] );
  794. }
  795. }
  796. for (var key in that.options.cropData) {
  797. if( that.options.cropData.hasOwnProperty(key) ) {
  798. formData.append( key , that.options.cropData[key] );
  799. }
  800. }
  801. $.ajax({
  802. url: that.options.cropUrl,
  803. data: formData,
  804. context: document.body,
  805. cache: false,
  806. contentType: false,
  807. processData: false,
  808. type: 'POST'
  809. }).always(function (data) {
  810. that.afterCrop(data);
  811. });
  812. }
  813. //
  814. },
  815. afterCrop: function (data) {
  816. var that = this;
  817. that.colorOnClick(true);
  818. try {
  819. response = jQuery.parseJSON(data);
  820. }
  821. catch(err) {
  822. response = typeof data =='object' ? data : jQuery.parseJSON(data);
  823. }
  824. if (response.status == 'success') {
  825. if (that.options.imgEyecandy)
  826. that.imgEyecandy.hide();
  827. that.destroy();
  828. that.saveImgUrl='product_image_crop_md5,'+response.md5+','+response.url;
  829. var croppedImg='<img class="croppedImg" src="' + response.url + '">';
  830. that.obj.append(croppedImg);
  831. if (that.options.outputUrlId !== '') { $('#' + that.options.outputUrlId).val(response.url); }
  832. that.croppedImg = that.obj.find('.croppedImg');
  833. that.croppedImg .width(that.objW+"px").height(that.objH+"px");
  834. that.init();
  835. that.hideLoader();
  836. that.imgUploadControl.hide();
  837. that.cropSaveControl.show();
  838. }
  839. if (response.status == 'error') {
  840. if (that.options.onError) that.options.onError.call(that,response.message);
  841. that.hideLoader();
  842. that.cropControlsCrop.show();
  843. }
  844. if (that.options.onAfterImgCrop) that.options.onAfterImgCrop.call(that, response);
  845. },
  846. showLoader:function(){
  847. var that = this;
  848. that.obj.append(that.options.loaderHtml);
  849. that.loader = that.obj.find('.loader');
  850. },
  851. hideLoader:function(){
  852. var that = this;
  853. that.loader.remove();
  854. },
  855. reset:function(){
  856. var that = this;
  857. that.destroy();
  858. that.init();
  859. that.imgUploadControl.show();
  860. if( !$.isEmptyObject(that.croppedImg)){
  861. that.obj.append(that.croppedImg);
  862. if(that.options.outputUrlId !== ''){ $('#'+that.options.outputUrlId).val(that.croppedImg.attr('url')); }
  863. }
  864. if (typeof that.options.onReset == 'function')
  865. that.options.onReset.call(that);
  866. },
  867. destroy:function(){
  868. var that = this;
  869. that.colorOnClick(true);
  870. if(that.options.modal && !$.isEmptyObject(that.modal) ){ that.destroyModal(); }
  871. if(that.options.imgEyecandy && !$.isEmptyObject(that.imgEyecandy) ){ that.destroyEyecandy(); }
  872. if( !$.isEmptyObject( that.cropControlsUpload ) ){ that.cropControlsUpload.remove(); }
  873. if( !$.isEmptyObject( that.cropControlsCrop ) ){ that.cropControlsCrop.remove(); }
  874. if( !$.isEmptyObject( that.loader ) ){ that.loader.remove(); }
  875. if( !$.isEmptyObject( that.form ) ){ that.form.remove(); }
  876. that.obj.html('');
  877. },
  878. isAjaxUploadSupported: function () {
  879. var input = document.createElement("input");
  880. input.type = "file";
  881. return (
  882. "multiple" in input &&
  883. typeof File != "undefined" &&
  884. typeof FormData != "undefined" &&
  885. typeof (new XMLHttpRequest()).upload != "undefined");
  886. },
  887. CreateFallbackIframe: function () {
  888. var that = this;
  889. if (!that.isAjaxUploadSupported()) {
  890. if (jQuery.isEmptyObject(that.iframeobj)) {
  891. var iframe = document.createElement("iframe");
  892. iframe.setAttribute("id", that.id + "_upload_iframe");
  893. iframe.setAttribute("name", that.id + "_upload_iframe");
  894. iframe.setAttribute("width", "0");
  895. iframe.setAttribute("height", "0");
  896. iframe.setAttribute("border", "0");
  897. iframe.setAttribute("src", "javascript:false;");
  898. iframe.style.display = "none";
  899. document.body.appendChild(iframe);
  900. } else {
  901. iframe = that.iframeobj[0];
  902. }
  903. var myContent = '<!DOCTYPE html>'
  904. + '<html><head><title>Uploading File</title></head>'
  905. + '<body>'
  906. + '<form '
  907. + 'class="' + that.id + '_upload_iframe_form" '
  908. + 'name="' + that.id + '_upload_iframe_form" '
  909. + 'action="' + that.options.uploadUrl + '" method="post" '
  910. + 'enctype="multipart/form-data" encoding="multipart/form-data" style="display:none;">'
  911. + $("#" + that.id + '_imgUploadField')[0].outerHTML
  912. + '</form></body></html>';
  913. iframe.contentWindow.document.open('text/htmlreplace');
  914. iframe.contentWindow.document.write(myContent);
  915. iframe.contentWindow.document.close();
  916. that.iframeobj = $("#" + that.id + "_upload_iframe");
  917. that.iframeform = that.iframeobj.contents().find("html").find("." + that.id + "_upload_iframe_form");
  918. that.iframeform.on("change", "input", function () {
  919. that.SubmitFallbackIframe(that);
  920. });
  921. that.iframeform.find("input")[0].attachEvent("onchange", function () {
  922. that.SubmitFallbackIframe(that);
  923. });
  924. var eventHandlermyFile = function () {
  925. if (iframe.detachEvent)
  926. iframe.detachEvent("onload", eventHandlermyFile);
  927. else
  928. iframe.removeEventListener("load", eventHandlermyFile, false);
  929. var response = that.getIframeContentJSON(iframe);
  930. if (jQuery.isEmptyObject(that.modal)) {
  931. that.afterUpload(response);
  932. }
  933. }
  934. if (iframe.addEventListener)
  935. iframe.addEventListener("load", eventHandlermyFile, true);
  936. if (iframe.attachEvent)
  937. iframe.attachEvent("onload", eventHandlermyFile);
  938. return "#" + that.id + '_imgUploadField';
  939. } else {
  940. return "";
  941. }
  942. },
  943. SubmitFallbackIframe: function (that) {
  944. that.showLoader();
  945. if(that.options.processInline && !that.options.uploadUrl){
  946. if (that.options.onError){
  947. that.options.onError.call(that,"processInline is not supported by your browser ");
  948. that.hideLoader();
  949. }
  950. }else{
  951. if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
  952. that.iframeform[0].submit();
  953. }
  954. },
  955. getIframeContentJSON: function (iframe) {
  956. try {
  957. var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document,
  958. response;
  959. var innerHTML = doc.body.innerHTML;
  960. if (innerHTML.slice(0, 5).toLowerCase() == "<pre>" && innerHTML.slice(-6).toLowerCase() == "</pre>") {
  961. innerHTML = doc.body.firstChild.firstChild.nodeValue;
  962. }
  963. response = jQuery.parseJSON(innerHTML);
  964. } catch (err) {
  965. response = { success: false };
  966. }
  967. return response;
  968. },
  969. hexadecimal:function(num) {
  970. var r = parseInt(num).toString(16);
  971. if (r.length == 1) {
  972. return '0' + r;
  973. }
  974. return r.toUpperCase();
  975. }
  976. };
  977. })(window, document);