ImageClipper.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. o2.widget = o2.widget || {};
  2. o2.widget.ImageClipper = o2.ImageClipper = new Class({
  3. Implements: [Options, Events],
  4. Extends: o2.widget.Common,
  5. options: {
  6. "style": "default",
  7. "path": o2.session.path+"/widget/$ImageClipper/",
  8. "imageUrl" : "",
  9. "action" : null, //上传服务,可选,如果不设置,使用公共图片服务
  10. "method": "", //使用action 的方法
  11. "parameter": {}, //action 时的url参数
  12. "data": null, //formdata 的data, H5有效
  13. "reference": "", //使用公共图片服务上传时的参数
  14. "referenceType" : "", //使用公共图片服务上传时的参数, 目前支持 processPlatformJob, processPlatformForm, portalPage, cmsDocument, forumDocument
  15. "description" : "",
  16. "aspectRatio" : 1, //生成图片的宽高比, 0 表示不限制
  17. "resultMaxSize" : 800, //生成图片的最大宽或高
  18. "editorSize" : 340, //H5有效,图形容器
  19. "frameMinSize" : 30, //H5有效, 选择框的最小宽度
  20. "previewerSize" : 260, //H5有效, 预览区域大小
  21. "showPreviewer" : true, //H5有效
  22. "fromLocalEnable" : true, //H5有效,本地图片
  23. "fromFileEnable" : true, //H5有效,云文件图片
  24. "resetEnable" : false, //H5有效
  25. "uploadSourceEnable" : true //H5有效
  26. },
  27. initialize: function(node, options){
  28. this.node = node;
  29. if( isNaN( options.aspectRatio ) )options.aspectRatio = 0;
  30. if( isNaN( options.resultMaxSize ) )options.resultMaxSize = 800;
  31. this.setOptions(options);
  32. this.path = this.options.path || (o2.session.path+"/widget/$ImageClipper/");
  33. this.cssPath = this.path + this.options.style+"/css.wcss";
  34. this._loadCss();
  35. this.fireEvent("init");
  36. },
  37. load: function( imageBase64 ){
  38. this.container = new Element("div.container", { styles : this.css.container}).inject(this.node);
  39. this.container.addEvent("selectstart", function(e){
  40. e.preventDefault();
  41. e.stopPropagation();
  42. });
  43. if( this.checkBroswer() ){
  44. //this._loadWithSWF();
  45. this._loadWithH5( imageBase64 );
  46. }else{
  47. this._loadWithSWF();
  48. }
  49. },
  50. _loadWithSWF : function(){
  51. this.clipper = new o2.widget.FlashImageClipper( this.container, this.options, this );
  52. this.clipper.load()
  53. },
  54. _loadWithH5 : function( imageBase64 ){
  55. this.clipper = new o2.widget.HTML5ImageClipper( this.container, this.options, this );
  56. this.clipper.load( imageBase64 )
  57. },
  58. uploadImage: function( success, failure ){
  59. this.clipper.uploadImage( success, failure )
  60. },
  61. getFormData : function(){
  62. return this.clipper.getFormData()
  63. },
  64. getResizedImage : function(){
  65. return this.clipper.getResizedImage();
  66. },
  67. getBase64Code : function(){
  68. return this.clipper.getBase64Code();
  69. },
  70. getBase64Image: function(){
  71. return this.clipper.getBase64Image();
  72. },
  73. close : function(){
  74. this.clipper.close();
  75. },
  76. checkBroswer : function(){
  77. if( window.Uint8Array && window.HTMLCanvasElement && window.atob && window.Blob){
  78. this.available = true;
  79. return true;
  80. }else{
  81. this.available = false;
  82. //this.container.set("html", "<p>您的浏览器不支持以下特性:</p><ul><li>canvas</li><li>Blob</li><li>Uint8Array</li><li>FormData</li><li>atob</li></ul>");
  83. return false;
  84. }
  85. }
  86. });
  87. o2.widget.FlashImageClipper = new Class({
  88. Implements: [Options, Events],
  89. options: {
  90. "style": "default",
  91. "path": o2.session.path+"/widget/$ImageClipper/",
  92. "imageUrl" : "",
  93. "action" : null, //可选,如果不设置,使用公共图片服务
  94. "method": "", //使用action 的方法
  95. "parameter": {}, //action 时的url参数
  96. "reference": "", //使用公共图片服务上传时的参数
  97. "referenceType" : "", //使用公共图片服务上传时的参数, 目前支持 processPlatformJob, processPlatformForm, portalPage, cmsDocument, forumDocument
  98. "description" : "",
  99. "aspectRatio" : 1, //生成图片的宽高比, 0 表示不限制
  100. "resultMaxSize" : 800 //生成图片的最大宽或高
  101. },
  102. initialize: function(node, options, parent){
  103. this.container = node;
  104. this.setOptions(options);
  105. this.parent = parent;
  106. if( !this.options.aspectRatio ){
  107. this.options.aspectRatio = 1;
  108. }
  109. //this.path = this.options.path || (o2.session.path+"/widget/$ImageClipper/");
  110. //this.cssPath = this.path + this.options.style+"/css.wcss";
  111. this.Previer_MaxSize = 240;
  112. this.css = this.parent.css;
  113. this.fireEvent("init");
  114. },
  115. load : function(){
  116. window.uploadevent_flash = function( value ){
  117. if( typeOf( value ) == "number" ){
  118. value += '';
  119. switch(value){
  120. case '1':
  121. alert("上传成功!");
  122. var time = new Date().getTime();
  123. ok();
  124. break;
  125. case '2':
  126. if( this.isUploading ){
  127. return 0;
  128. }else{
  129. this.isUploading = true;
  130. return 1;
  131. }
  132. //if(confirm('js call upload')){
  133. // return 1;
  134. //}else{
  135. // return 0;
  136. //}
  137. break;
  138. case '-1':
  139. this.isUploading = false;
  140. //alert("您已取消!");
  141. //cancel();
  142. break;
  143. case '-2':
  144. this.isUploading = false;
  145. alert("上传失败,请重新上传!");
  146. window.location.href = "#";
  147. break;
  148. default:
  149. //alert(typeof(status) + ' ' + status);
  150. }
  151. }else{
  152. this.isUploading = false;
  153. var json = JSON.parse( value );
  154. if( json.type == "error" ){
  155. alert( json.message );
  156. }else{
  157. if(this.uploadSuccess)this.uploadSuccess( json.data );
  158. }
  159. }
  160. }.bind(this);
  161. this.getUploadUrl( function(){
  162. this.renderFlash()
  163. }.bind(this));
  164. },
  165. renderFlash : function(){
  166. this.contentNode = new Element("div.contentNode", {
  167. styles : this.css.contentNode,
  168. id : "imageclipper_swf"
  169. }).inject(this.container);
  170. var path = o2.session.path+"/widget/$ImageClipper/";
  171. var imageUrl = this.options.imageUrl || path + "flash_default.png";
  172. if( this.options.aspectRatio > 1 ){
  173. var previewerWidth = this.Previer_MaxSize;
  174. var previewerHeight = this.Previer_MaxSize / this.options.aspectRatio;
  175. }else{
  176. var previewerWidth = this.Previer_MaxSize * this.options.aspectRatio;
  177. var previewerHeight = this.Previer_MaxSize;
  178. }
  179. COMMON.AjaxModule.load( path +"swfobject.js", function () {
  180. swfobject.embedSWF( path+"FaustCplus.swf", this.contentNode, "650", "370", "9.0.0", path+"expressInstall.swf", {
  181. "jsfunc":"uploadevent_flash",
  182. "imgUrl": imageUrl,
  183. "tip" : this.options.description,
  184. "aspectRatio" : this.options.aspectRatio,
  185. "reqContentDisposition" : "", //"" 或者 formData
  186. "imageUploadKey" : "thumb.jpg", //reqContentDisposition 为 formdata 时候有效,文件名称
  187. "imageSrcUploadKey" : "src.jpg", //reqContentDisposition 为 formdata 时候有效,文件名称
  188. "showZoom" : false,
  189. "showSaveBtns" : false,
  190. "showTurn" : false,
  191. "showColorAdjuster" : false,
  192. "pid":"75642723",
  193. "uploadSrc":false,
  194. "showBrow":true,
  195. "showCame":false,
  196. "pSize":"300|300|"+previewerWidth+"|"+previewerHeight, //|80|40|40|20"//,
  197. "uploadUrl": this.uploadUrl //+encodeURI("<计算的值>")+"?shortname=<计算的值>?filepath=<计算的值>?sizes=160|80|40?imgnames=face.jpg|face_medium.jpg|face_small.jpg" //sizes 几张图片的比例
  198. }, {
  199. menu: "false",
  200. scale: "noScale",
  201. allowFullscreen: "true",
  202. allowScriptAccess: "always",
  203. wmode:"transparent",
  204. bgcolor: "#FFFFFF"
  205. }, {
  206. id:"FaustCplus"
  207. }, function( swf ){
  208. this.swf = swf;
  209. }.bind(this));
  210. }.bind(this))
  211. },
  212. getUploadUrl : function( callback ){
  213. if( this.options.action ){
  214. this.action = (typeOf(this.options.action)=="string") ? o2.Actions.get(action).action : this.options.action;
  215. this.action.getActions(function(){
  216. var url = this.action.actions[this.options.method];
  217. url = this.action.address+url.uri;
  218. if(this.options.parameter){
  219. Object.each(this.options.parameter, function(v, k){
  220. url = url.replace("{"+k+"}", v);
  221. });
  222. }
  223. this.uploadUrl = url;
  224. if(callback)callback(url);
  225. }.bind(this));
  226. }else{
  227. //公共图片服务
  228. var addressObj = layout.desktop.serviceAddressList["x_file_assemble_control"];
  229. if (addressObj){
  230. var address = layout.config.app_protocol+"//"+addressObj.host+(addressObj.port==80 ? "" : ":"+addressObj.port)+addressObj.context;
  231. }else{
  232. var host = layout.config.center.host || window.location.hostname;
  233. var port = layout.config.center.port;
  234. var address = layout.config.app_protocol+"//"+host+(port=="80" ? "" : ":"+port)+"/x_program_center";
  235. }
  236. var url = "/jaxrs/file/upload/referencetype/"+ this.options.referenceType + "/reference/" + this.options.reference + "/scale/" + this.options.resultMaxSize;
  237. this.uploadUrl = address+url;
  238. if(callback)callback(this.uploadUrl);
  239. }
  240. },
  241. uploadImage: function( success, failure ){
  242. this.uploadSuccess = success;
  243. if( this.swf ){
  244. this.swf.ref["jscall_updateAvatar"](); //JsCallAs是flash里addCallback的函数
  245. }
  246. },
  247. getFormData : function(){
  248. return true;
  249. },
  250. getResizedImage : function(){
  251. return true;
  252. },
  253. getBase64Code : function(){
  254. return true;
  255. },
  256. getBase64Image: function(){
  257. return true;
  258. },
  259. close : function(){
  260. }
  261. });
  262. o2.widget.HTML5ImageClipper = new Class({
  263. Implements: [Options, Events],
  264. options: {
  265. "style": "default",
  266. "path": o2.session.path+"/widget/$ImageClipper/",
  267. "imageUrl" : "",
  268. "editorSize" : 340, //图形容器
  269. "aspectRatio" : 1, //生成图片的宽高比, 0 表示不限制
  270. "frameMinSize" : 30, //选择框的最小宽度
  271. "previewerSize" : 260, //预览区域大小
  272. "resultMaxSize" : 800, //生成图片的最大宽或高
  273. "action" : null, //可选,如果不设置,使用公共图片服务
  274. "method": "", //使用action 的方法
  275. "parameter": {}, //action 时的url参数
  276. "data": null, //formdata 的data
  277. "reference": "", //使用公共图片服务上传时的参数
  278. "referenceType" : "", //使用公共图片服务上传时的参数, 目前支持 processPlatformJob, processPlatformForm, portalPage, cmsDocument, forumDocument
  279. "uploadSourceEnable" : true, //是否允许上传原图
  280. "showPreviewer" : true,
  281. "fromLocalEnable" : true, //本地图片
  282. "fromFileEnable" : true, //云文件图片
  283. "resetEnable" : false,
  284. "description" : ""
  285. },
  286. initialize: function(node, options, parent){
  287. this.container = node;
  288. this.setOptions(options);
  289. this.parent = parent;
  290. //this.path = this.options.path || (o2.session.path+"/widget/$ImageClipper/");
  291. //this.cssPath = this.path + this.options.style+"/css.wcss";
  292. this.fileName = "untitled.png";
  293. this.fileType = "image/png";
  294. this.fileSize = null;
  295. this.css = this.parent.css;
  296. this.fireEvent("init");
  297. },
  298. load : function( imageBase64 ){
  299. this.lastPoint=null;
  300. this.loadToolBar();
  301. this.contentNode = new Element("div.contentNode", { styles : this.css.contentNode}).inject(this.container);
  302. this.loadEditorNode();
  303. this.loadResultNode();
  304. if( this.options.description ){
  305. this.loadDescriptionNode();
  306. }
  307. if( this.options.imageUrl ){
  308. this.loadImageAsUrl( this.options.imageUrl );
  309. }
  310. if( imageBase64 ){
  311. this.loadImageAsFile( this.base64ToBlob( imageBase64 ) );
  312. }
  313. },
  314. uploadImage: function( success, failure ){
  315. if( this.resizedImage ){
  316. if( this.options.action ){
  317. this.action = (typeOf(this.options.action)=="string") ? o2.Actions.get(action).action : this.options.action;
  318. this.action.invoke({
  319. "name": this.options.method,
  320. "async": true,
  321. "data": this.getFormData(),
  322. "file": this.resizedImage,
  323. "parameter": this.options.parameter,
  324. "success": function(json){
  325. success(json)
  326. }.bind(this)
  327. });
  328. }else{
  329. //公共图片上传服务
  330. var maxSize = this.options.resultMaxSize;
  331. if( this.uploadSourceInput && this.uploadSourceInput.get("checked") ){
  332. maxSize = 0; //上传原图
  333. }
  334. o2.xDesktop.uploadImageByScale(
  335. this.options.reference,
  336. this.options.referenceType,
  337. maxSize,
  338. this.getFormData(),
  339. this.resizedImage,
  340. success,
  341. failure
  342. );
  343. }
  344. }else{
  345. }
  346. },
  347. getFormData : function(){
  348. var formData = new FormData();
  349. formData.append('file',this.resizedImage, this.fileName );
  350. if( this.options.data ){
  351. Object.each(this.options.data, function(v, k){
  352. formData.append(k, v)
  353. });
  354. }
  355. return formData;
  356. },
  357. getResizedImage : function(){
  358. return this.resizedImage;
  359. },
  360. getBase64Code : function(){
  361. return this.base64Code;
  362. },
  363. getBase64Image: function(){
  364. if( !this.base64Code )return null;
  365. return 'data:'+ this.fileType +';base64,' + this.base64Code;
  366. },
  367. checkBroswer : function(){
  368. if( window.Uint8Array && window.HTMLCanvasElement && window.atob && window.Blob){
  369. this.available = true;
  370. return true;
  371. }else{
  372. this.available = false;
  373. //this.container.set("html", "<p>您的浏览器不支持以下特性:</p><ul><li>canvas</li><li>Blob</li><li>Uint8Array</li><li>FormData</li><li>atob</li></ul>");
  374. return false;
  375. }
  376. },
  377. close : function(){
  378. this.docBody.removeEvent("touchmove",this.bodyMouseMoveFun);
  379. this.docBody.removeEvent("mousemove",this.bodyMouseMoveFun);
  380. this.docBody.removeEvent("touchend",this.bodyMouseEndFun);
  381. this.docBody.removeEvent("mouseup",this.bodyMouseEndFun);
  382. this.container.destroy();
  383. delete this;
  384. },
  385. loadToolBar: function(){
  386. this.uploadToolbar = new Element("div.uploadToolbar", {
  387. "styles" : this.css.uploadToolbar
  388. }).inject(this.container);
  389. //var width = this.options.editorSize;
  390. //this.uploadToolbar.setStyle( "width" , width+ "px");
  391. if( this.options.fromLocalEnable ){
  392. this.uploadLocalImage = new Element("button.uploadActionNode",{
  393. "styles" : this.css.uploadActionNode,
  394. "text" : "选择本地图片"
  395. }).inject(this.uploadToolbar);
  396. this.uploadLocalImage.addEvents({
  397. "click": function(){ this.fileNode.click(); }.bind(this)
  398. });
  399. this.fileNode = new Element("input.file", {
  400. "type" : "file",
  401. "accept":"images/*",
  402. "styles" : {"display":"none"}
  403. }).inject(this.container);
  404. this.fileNode.addEvent("change", function(event){
  405. var file=this.fileNode.files[0];
  406. this.fileType = file.type;
  407. this.fileName = file.name;
  408. this.fileSize = file.size;
  409. this.loadImageAsFile( file );
  410. }.bind(this));
  411. }
  412. this._createUploadButtom();
  413. this.uploadCloudFileArea = new Element("span").inject( this.uploadToolbar );
  414. if( this.options.fromFileEnable ){
  415. var url = o2.session.path+"/xDesktop/$Layout/applications.json";
  416. o2.getJSON(url, function(json){
  417. json.each( function(obj){
  418. if( obj.name == "File" || obj.path == "File" ){
  419. this.uploadCloudFile = new Element("button.uploadActionNode",{
  420. "styles" : this.css.uploadActionNode,
  421. "text" : "选择云文件图片"
  422. }).inject(this.uploadCloudFileArea );
  423. this.uploadCloudFile.addEvents({
  424. "click": function(){ this.selectFileImage(
  425. function( url, id ,attachmentInfo ){
  426. this.fileName = attachmentInfo.name;
  427. this.fileType = ["jpeg","jpg"].contains( attachmentInfo.extension.toLowerCase() ) ? "image/jpeg" : "image/png" ;
  428. this.fileSize = attachmentInfo.length;
  429. this.loadImageAsUrl( url );
  430. }.bind(this)
  431. ); }.bind(this)
  432. });
  433. }
  434. }.bind(this));
  435. }.bind(this));
  436. }
  437. if( this.options.resetEnable ){
  438. this.resetAction = new Element("button.resetAction",{
  439. "styles" : this.css.resetActionNode,
  440. "text" : "重置"
  441. }).inject(this.uploadToolbar);
  442. this.resetAction.addEvents({
  443. "click": function(){ this.reset(); }.bind(this)
  444. });
  445. }
  446. if( this.options.uploadSourceEnable ){
  447. this.uploadSourceInput = new Element( "input", {
  448. type : "checkbox",
  449. events : {
  450. change : function(){
  451. this.clipImage();
  452. }.bind(this)
  453. }
  454. }).inject( this.uploadToolbar );
  455. new Element("span",{
  456. text : "上传原图"
  457. }).inject( this.uploadToolbar );
  458. }
  459. },
  460. _createUploadButtom : function(){
  461. },
  462. reset: function(){
  463. this.fileName = "untitled.png";
  464. this.fileType = "image/png";
  465. this.fileSize = null;
  466. this.resizedImage = "";
  467. this.base64Code = "";
  468. this.resetImage();
  469. this.setFrameSize({width:0, height:0});
  470. this.frameOffset.top = 0;
  471. this.frameOffset.left = 0;
  472. this.frameNode.setStyles({
  473. top:0,
  474. left:0
  475. });
  476. this.resultNode.empty();
  477. this.editorContainer.setStyles( this.css.editorContainer );
  478. this.imageNode.setStyle("display","none");
  479. this.innerNode.setStyles({
  480. "width" : 0,
  481. "height" : 0
  482. })
  483. },
  484. selectFileImage : function( callback ){
  485. var _self = this;
  486. o2.xDesktop.requireApp("File", "FileSelector", function(){
  487. _self.selector_cloud = new o2.xApplication.File.FileSelector( document.body ,{
  488. "style" : "default",
  489. "title": "选择云文件图片",
  490. "copyToPublic" : false,
  491. //"reference" : _self.options.reference,
  492. //"referenceType" : _self.options.referenceType,
  493. "listStyle": "preview",
  494. "selectType" : "images",
  495. "onPostSelectAttachment" : function( url, id, attachmentInfor ){
  496. if(callback)callback(url, id, attachmentInfor );
  497. }
  498. });
  499. _self.selector_cloud.load();
  500. }, true);
  501. },
  502. loadResultNode: function(){
  503. if( this.options.showPreviewer ){
  504. this.resultContainer = new Element("div", {"styles":this.css.resultContainer}).inject(this.contentNode);
  505. var containerHeight = Math.max( this.options.editorSize ,this.options.previewerSize ) - (parseInt(this.resultContainer.getStyle("padding-left"))*2);
  506. this.resultContainer.setStyles( {
  507. "width": this.options.previewerSize+"px",
  508. "height": containerHeight +"px"
  509. } );
  510. this.resultTitleNode = new Element("div", {
  511. "styles":this.css.resultTitleNode,
  512. "text" : "预览"
  513. }
  514. ).inject(this.resultContainer);
  515. var titleHeight = this.resultTitleNode.getSize().y;
  516. var nodeHeight = this.options.aspectRatio ? ( this.options.previewerSize / this.options.aspectRatio) : this.options.previewerSize ;
  517. this.resultNode = new Element("div.resultNode", {
  518. "styles":this.css.resultNode
  519. }).inject(this.resultContainer);
  520. this.resultNode.setStyles( {
  521. "padding-top": (containerHeight-titleHeight-nodeHeight)/2 - 10 +"px"
  522. } );
  523. }else{
  524. this.resultNode = new Element("div", {
  525. styles : {display : "none"}
  526. }).inject(this.contentNode);
  527. }
  528. },
  529. loadEditorNode: function(){
  530. this.docBody = window.document.body;
  531. this.editorContainer = new Element("div.editorContainer", { styles : this.css.editorContainer}).inject(this.contentNode);
  532. this.editorContainer.setStyles( {
  533. "width": this.options.editorSize+"px",
  534. "height": this.options.editorSize+"px"
  535. } );
  536. this.editorNode = new Element("div.editorNode", { styles : this.css.editorNode}).inject(this.editorContainer);
  537. this.innerNode = new Element("div.innerNode",{ styles : this.css.innerNode } ).inject(this.editorNode);
  538. this.imageNode = new Element("img",{
  539. styles : this.css.imageNode
  540. }).inject(this.innerNode);
  541. this.imageNode.ondragstart = function(){
  542. return false;
  543. };
  544. this.frameNode = new Element("div.frameNode",{ styles : this.css.frameNode }).inject(this.innerNode);
  545. this.frameOffset={ top:0, left:0 };
  546. this.frameNode.addEvents({
  547. "touchstart" : function(ev){ this.getOffset(ev) }.bind(this),
  548. "mousedown" : function(ev){ this.getOffset(ev) }.bind(this),
  549. "touchmove" : function(ev){
  550. if(!this.lastPoint)return;
  551. var offset= this.getOffset(ev);
  552. if( this.resizeMode ){
  553. this.resizeFrames( offset );
  554. }else{
  555. this.moveFrames( offset );
  556. }
  557. ev.stopPropagation();
  558. }.bind(this),
  559. "mousemove" : function(ev){
  560. if(!this.lastPoint)return;
  561. var offset= this.getOffset(ev);
  562. if( this.resizeMode ){
  563. this.resizeFrames( offset );
  564. }else{
  565. this.moveFrames( offset );
  566. }
  567. ev.stopPropagation();
  568. }.bind(this),
  569. "touchend" : function(ev){
  570. this.lastPoint=null;
  571. if( this.resizeMode ){
  572. this.frameNode.setStyle("cursor", "move" );
  573. this.docBody.setStyle("cursor", "default" );
  574. this.resizeMode = false;
  575. }
  576. this.clipImage();
  577. ev.stopPropagation();
  578. }.bind(this),
  579. "mouseup" : function(ev){
  580. this.lastPoint=null;
  581. if( this.resizeMode ){
  582. this.frameNode.setStyle("cursor", "move" );
  583. this.docBody.setStyle("cursor", "default" );
  584. this.resizeMode = false;
  585. }
  586. this.clipImage();
  587. ev.stopPropagation();
  588. }.bind(this)
  589. });
  590. this.reizeNode = new Element("div.reizeNode",{ styles : this.css.reizeNode }).inject(this.frameNode);
  591. this.reizeNode.addEvents({
  592. "touchstart" : function(ev){
  593. this.frameNode.setStyle("cursor", "nw-resize" );
  594. this.docBody.setStyle("cursor", "nw-resize" );
  595. this.resizeMode = true;
  596. this.getOffset(ev);
  597. ev.stopPropagation();
  598. }.bind(this),
  599. "mousedown" : function(ev){
  600. this.frameNode.setStyle("cursor", "nw-resize" );
  601. this.docBody.setStyle("cursor", "nw-resize" );
  602. this.resizeMode = true;
  603. this.getOffset(ev);
  604. ev.stopPropagation();
  605. }.bind(this),
  606. "touchmove" : function(ev){
  607. if(!this.lastPoint)return;
  608. var offset= this.getOffset(ev);
  609. this.resizeFrames( offset );
  610. ev.stopPropagation();
  611. }.bind(this),
  612. "mousemove" : function(ev){
  613. if(!this.lastPoint)return;
  614. var offset= this.getOffset(ev);
  615. this.resizeFrames( offset );
  616. ev.stopPropagation();
  617. }.bind(this),
  618. "touchend" : function(ev){
  619. this.frameNode.setStyle("cursor", "move" );
  620. this.docBody.setStyle("cursor", "default" );
  621. this.resizeMode = false;
  622. this.lastPoint=null;
  623. this.clipImage();
  624. ev.stopPropagation();
  625. }.bind(this),
  626. "mouseup" : function(ev){
  627. this.frameNode.setStyle("cursor", "move" );
  628. this.docBody.setStyle("cursor", "default" );
  629. this.resizeMode = false;
  630. this.lastPoint=null;
  631. this.clipImage();
  632. ev.stopPropagation();
  633. }.bind(this)
  634. });
  635. this.bodyMouseMoveFun = this.bodyMouseMove.bind(this);
  636. this.docBody.addEvent("touchmove", this.bodyMouseMoveFun);
  637. this.docBody.addEvent("mousemove", this.bodyMouseMoveFun);
  638. this.bodyMouseEndFun = this.bodyMouseEnd.bind(this);
  639. this.docBody.addEvent("touchend", this.bodyMouseEndFun);
  640. this.docBody.addEvent("mouseup", this.bodyMouseEndFun);
  641. },
  642. loadDescriptionNode: function(){
  643. new Element("div",{
  644. "styles": this.css.descriptionNode,
  645. "text": this.options.description
  646. }).inject( this.container )
  647. },
  648. bodyMouseMove: function(ev){
  649. if(!this.lastPoint)return;
  650. if( this.resizeMode ){
  651. var offset= this.getOffset(ev);
  652. this.resizeFrames( offset );
  653. }
  654. },
  655. bodyMouseEnd: function(ev){
  656. this.lastPoint=null;
  657. if( this.resizeMode ){
  658. this.frameNode.setStyle("cursor", "move" );
  659. this.docBody.setStyle("cursor", "default" );
  660. this.resizeMode = false;
  661. this.clipImage();
  662. }
  663. },
  664. clipImage: function(){
  665. this.resultNode.empty();
  666. var nh=this.imageNode.naturalHeight,
  667. nw=this.imageNode.naturalWidth,
  668. max = (this.uploadSourceInput && this.uploadSourceInput.get("checked")) ? 0 : this.options.resultMaxSize,
  669. size,
  670. ratio;
  671. ratio = this.options.aspectRatio ? this.options.aspectRatio : (this.frameOffset.size.width / this.frameOffset.size.height );
  672. if( max == 0 || ( nh<=max && nw<=max )){
  673. size = this.getRatioMaxSize(nw, nh , ratio);
  674. }else{
  675. var min = Math.min(max, nh, nw);
  676. size = this.getRatioMaxSize(min, min, ratio);
  677. }
  678. var canvas = new Element("canvas", size);
  679. var ctx=canvas.getContext('2d'),
  680. scale=nw/this.offset.width,
  681. x=this.frameOffset.left*scale,
  682. y=this.frameOffset.top*scale,
  683. w=this.frameOffset.size.width*scale,
  684. h=this.frameOffset.size.height*scale;
  685. ctx.drawImage(this.imageNode,x,y,w,h,0,0,size.width,size.height);
  686. var src=canvas.toDataURL( this.fileType );
  687. this.canvas=canvas;
  688. canvas.inject(this.resultNode);
  689. src=src.split(',')[1];
  690. if(!src){
  691. this.resizedImage = null;
  692. this.base64Code = "";
  693. return;
  694. }
  695. this.base64Code = src;
  696. src=window.atob(src);
  697. var ia = new Uint8Array(src.length);
  698. for (var i = 0; i < src.length; i++) {
  699. ia[i] = src.charCodeAt(i);
  700. }
  701. this.resizedImage = new Blob([ia], {type: this.fileType });
  702. var min = Math.min(this.options.previewerSize, nh, nw, this.options.resultMaxSize);
  703. size = this.getRatioMaxSize(min, min, ratio);
  704. canvas.setStyles({
  705. width : size.width + "px",
  706. height : size.height + "px"
  707. });
  708. },
  709. loadImageAsFile: function( file ){
  710. this.resetImage();
  711. this.editorContainer.setStyles( this.css.editorContainer_active );
  712. this.imageNode.setStyle("display","");
  713. this.setFrameSize({width:0, height:0});
  714. this.frameOffset.top = 0;
  715. this.frameOffset.left = 0;
  716. this.frameNode.setStyles({
  717. top:0,
  718. left:0
  719. });
  720. var reader=new FileReader();
  721. reader.onload=function(){
  722. this.imageNode.src=reader.result;
  723. reader = null;
  724. //this.setImageSize();
  725. //this.setFrameSize( this.getDefaultSize() );
  726. //this.clipImage();
  727. this.onImageLoad();
  728. }.bind(this);
  729. reader.readAsDataURL(file);
  730. },
  731. loadImageAsUrl: function( url ){
  732. this.resetImage();
  733. this.editorContainer.setStyles( this.css.editorContainer_active );
  734. this.imageNode.setStyle("display","");
  735. this.setFrameSize({width:0, height:0});
  736. this.frameOffset.top = 0;
  737. this.frameOffset.left = 0;
  738. this.frameNode.setStyles({
  739. top:0,
  740. left:0
  741. });
  742. this.onImageLoadFun = this.onImageLoad.bind(this);
  743. this.imageNode.addEvent( "load",this.onImageLoadFun );
  744. this.imageNode.src = url;
  745. },
  746. onImageLoad: function(){
  747. var nh=this.imageNode.naturalHeight,
  748. nw=this.imageNode.naturalWidth;
  749. if( isNaN(nh) || isNaN(nw) || nh == 0 || nw == 0 ){
  750. setTimeout( function(){
  751. this.onImageLoad();
  752. }.bind(this), 100 );
  753. }else{
  754. this._onImageLoad();
  755. }
  756. },
  757. _onImageLoad: function(){
  758. this.setImageSize();
  759. this.setFrameSize( this.getDefaultSize() );
  760. this.clipImage();
  761. if(this.onImageLoadFun){
  762. this.imageNode.removeEvent("load", this.onImageLoadFun);
  763. this.onImageLoadFun = null;
  764. }
  765. },
  766. resetImage: function(){
  767. this.imageNode.src='';
  768. if( this.canvas )this.canvas.destroy();
  769. },
  770. setImageSize: function(){
  771. var nh=this.imageNode.naturalHeight,
  772. nw=this.imageNode.naturalWidth,
  773. size;
  774. if( nw > nh ){
  775. size = {
  776. width : this.options.editorSize,
  777. height : this.options.editorSize * (nh / nw)
  778. }
  779. }else{
  780. size = {
  781. width : this.options.editorSize * (nw / nh),
  782. height : this.options.editorSize
  783. }
  784. }
  785. //if( isNaN(size.width) || isNaN(size.height) ){
  786. // debugger;
  787. //}
  788. this.offset = size;
  789. this.imageNode.setStyles( size );
  790. },
  791. setFrameSize: function(size){
  792. this.frameOffset.size=size;
  793. return this.frameNode.setStyles({
  794. width:size.width+'px',
  795. height:size.height+'px'
  796. });
  797. },
  798. getDefaultSize: function(){
  799. this.innerNode.setStyles({
  800. "width" : this.offset.width,
  801. "height" : this.offset.height,
  802. "margin-left" : (this.options.editorSize-this.offset.width)/2 +"px",
  803. "margin-top" : (this.options.editorSize-this.offset.height)/2 +"px"
  804. });
  805. if( this.options.aspectRatio ){
  806. return this.getRatioMaxSize(this.offset.width, this.offset.height);
  807. }else{
  808. //var min = Math.min(this.offset.width, this.offset.height);
  809. //return { width : min, height : min };
  810. return {
  811. width : this.offset.width,
  812. height : this.offset.height
  813. };
  814. }
  815. },
  816. getRatioMaxSize: function( width, height , radio ){
  817. if( !radio )radio = this.options.aspectRatio;
  818. var r = width / height;
  819. if( r > radio ){
  820. return {
  821. width : height * radio,
  822. height : height
  823. }
  824. }else{
  825. return {
  826. width : width,
  827. height : width / radio
  828. }
  829. }
  830. },
  831. resizeFrames: function( offset ){
  832. var x=offset.x;
  833. if( x == 0 )return;
  834. var y=offset.y;
  835. if( y == 0 )return;
  836. var top=this.frameOffset.top,
  837. left=this.frameOffset.left,
  838. size=this.frameOffset.size,
  839. width=this.offset.width,
  840. height=this.offset.height,
  841. ratio = this.options.aspectRatio,
  842. w,
  843. h;
  844. if( ratio ){
  845. if( Math.abs(x)/Math.abs(y) > ratio ){
  846. if( x+size.width+left>width ){
  847. return;
  848. }else{
  849. w = x + size.width;
  850. h = w / ratio;
  851. if( h+top > height ){
  852. return;
  853. }
  854. }
  855. }else{
  856. if(y+size.height+top>height){
  857. return;
  858. }else{
  859. h = y+ size.height;
  860. w = h * ratio;
  861. }
  862. if( w+left > width ){
  863. return;
  864. }
  865. }
  866. }else{
  867. if( x+size.width+left>width ){
  868. return;
  869. }else{
  870. w = x + size.width
  871. }
  872. if(y+size.height+top>height){
  873. return;
  874. }else{
  875. h = y+ size.height;
  876. }
  877. }
  878. var minWidth = this.options.frameMinSize;
  879. var minHeight = ratio ? minWidth / ratio : minWidth;
  880. w=w< minWidth ?minWidth:w;
  881. h=h< minHeight ? minHeight:h;
  882. this.frameNode.setStyles({
  883. width:w+'px',
  884. height:h+'px'
  885. });
  886. this.frameOffset.size={
  887. width : w,
  888. height : h
  889. }
  890. },
  891. moveFrames: function(offset){
  892. var x=offset.x,
  893. y=offset.y,
  894. top=this.frameOffset.top,
  895. left=this.frameOffset.left,
  896. size=this.frameOffset.size,
  897. width=this.offset.width,
  898. height=this.offset.height;
  899. if(x+size.width+left>width){
  900. x=width-size.width;
  901. }else{
  902. x=x+left;
  903. }
  904. if(y+size.height+top>height){
  905. y=height-size.height;
  906. }else{
  907. y=y+top;
  908. }
  909. x=x<0?0:x;
  910. y=y<0?0:y;
  911. this.frameNode.setStyles({
  912. top:y+'px',
  913. left:x+'px'
  914. });
  915. this.frameOffset.top=y;
  916. this.frameOffset.left=x;
  917. },
  918. getOffset: function(event){
  919. event=event.event;
  920. var x,y;
  921. if(event.touches){
  922. var touch=event.touches[0];
  923. x=touch.clientX;
  924. y=touch.clientY;
  925. }else{
  926. x=event.clientX;
  927. y=event.clientY;
  928. }
  929. if(!this.lastPoint){
  930. this.lastPoint={
  931. x:x,
  932. y:y
  933. };
  934. }
  935. var offset={
  936. x:x-this.lastPoint.x,
  937. y:y-this.lastPoint.y
  938. };
  939. this.lastPoint={
  940. x:x,
  941. y:y
  942. };
  943. return offset;
  944. },
  945. base64ToBlob : function( base64 ){
  946. if( base64.substr( 0, 10 ) == 'data:image' ){
  947. var bytes=window.atob(base64.split(',')[1]); //去掉url的头,并转换为byte
  948. }else{
  949. var bytes=window.atob(base64)
  950. }
  951. //处理异常,将ascii码小于0的转换为大于0
  952. var ab = new ArrayBuffer(bytes.length);
  953. var ia = new Uint8Array(ab);
  954. for (var i = 0; i < bytes.length; i++) {
  955. ia[i] = bytes.charCodeAt(i);
  956. }
  957. return new Blob( [ab] , {type : this.fileType });
  958. }
  959. });