var $ctx = ""; try { $ctx = document.scripts[document.scripts.length - 1].src.substr(1).match(new RegExp("(\\?|&)ctx=([^&]*)(&|$)"))[2] || ""; } catch (e) { } var imgViewTool = { puid: '', yunToken: '', hasLoaded: false, needEdit: false,//是否需要编辑图片 imageViewer: null, //图片查看对象 imageEditor: null,//图片编辑对象 moveTimer: null, //监测鼠标是否移动的定时器 justShowToggleBtn: false, // 只显示切换图片按钮 不显示其他按钮 默认为false 显示所有按钮 loading: true, // 是否显示切换图片loading图标 默认显示 title: false, // 是否显示图片标题 默认不显示 navbar: false, // 是否显示底部缩略图 默认不显示 slideInfo: {}, // 自动轮播配置 loadFiles: function () { }, //加载js和css init: function () { }, //初始化图片查看 initViewImage: function () { },//初始化图片查看实例 initHtml: function () { },//添加查看按钮工具栏 initImageEditor: function () { },//初始化图片编辑 imgshown: function () { },//查看大图打开时调用 imgviewed: function () { },//查看大图展示出来时调用 loadExtentFile: function () { },//加载外部文件 unactiveViewBtn: function () { },//更新左右切换按钮状态 blobToFile: function (theBlob, fileName) { },//将blob转换为file base64ToBlob: function (data) { },//base64转blob closeEditMode: function () { },//关闭编辑模式 openEditMode: function () { },//打开编辑模式 uploadImg: function () { },//上传图片 downloadImg: function () { },//下载图片 hexToRGBa: function () { },//hex转rgba getBrushSettings: function () { },//获取画笔设置 activateShapeMode: function () { },//打开图像模式 activateTextMode: function () { },//打开文本模式 hideSubMenu: function () { },//关闭子级菜单 replaceImg: function () { },//替换原图 copyImg: function () { },//复制图片 forwardImg: function () { },//转发图片 saveCloudImg: function () { },//图片保存到云盘 getHost: function (url) { },//截取域名 isOpen: false, //是否打开,点击图片后为true,关闭图片为false activeObjectId: '', //当前激活的图形id shapeOptions: {fill: 'transparent', stroke: '', color: ''},//图形参数 shapeType: '',//形状 rect或circle previewUrl: '', //新图片url objectId: '', //新图片objectId imgTitle: '', //新图片title size: '', //新图片大小 file: '', //新图片file useColor: '',//常用颜色 groupwebDomain: '//groupweb.chaoxing.com', noteDomain: '//noteyd.chaoxing.com', panDomain: '//pan-yz.chaoxing.com', shareDomain: '//sharewh.chaoxing.com', } imgViewTool.currentHref = function () { var jsPath = document.currentScript && document.currentScript.src ? document.currentScript.src : function () { var js = document.scripts , last = js.length - 1 , src; for (var i = last; i > 0; i--) { if (js[i].readyState === 'interactive') { src = js[i].src; break; } if (js[i].src.indexOf('imgviewer.js') > -1) { src = js[i].src; break; } } return src || js[last].src; }(); imgViewTool.prefix = jsPath.substring(0, jsPath.indexOf('/res/')); jsPath = jsPath.substring(jsPath.indexOf('//') + 2, jsPath.lastIndexOf('/') + 1); return jsPath; }(); //获取镜像域名 try { if(!window.obj){ imgViewTool.noteDomain = imgViewTool.prefix; $.ajax({ type:'get', url: imgViewTool.noteDomain + '/apis/mirrorConfig', async:false, success:function(res){ if(res.result == 1){ imgViewTool.groupwebDomain = res.data.domainMap.GroupWebDomainHttps; imgViewTool.panDomain = res.data.domainMap.panDomainHttps; imgViewTool.shareDomain = res.data.domainMap.shareWhDomainHttps; } }, }); }else{ imgViewTool.groupwebDomain = window.obj.mirrorDomain.GroupWebDomainHttps; imgViewTool.noteDomain = window.obj.mirrorDomain.NoteDomainHttps; imgViewTool.panDomain = window.obj.mirrorDomain.panDomainHttps; imgViewTool.shareDomain = window.obj.mirrorDomain.shareWhDomainHttps; } } catch (e) { } /*初始化 * params needEdit:是否需要编辑功能 * params options * type:edit或detail 编辑模式 */ imgViewTool.init = function (needEdit, options = {}) { if (imgViewTool.hasLoaded) { return; } if (typeof jQuery == 'undefined') { imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + '/res/js/common/jquery-3.7.1.min.js', "js"); imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + '/res/js/common/jquery-migrate-3.4.1.min.js', "js"); } if(window.obj && window.obj.mirrorDomain && (window.obj.mirrorDomain.isMirrorDeploy || window.obj.mirrorDomain.isMirrorDeploy == false && window.obj.mirrorDomain.NoteDomain.indexOf('chaoxing.com') == -1)){ $('#imgtoolWrap #imgReport,#imgtoolWrap #imgForward,#imgtoolWrap #imgSaveCloud,#imgtoolWrap #imgDownload').remove(); } if(options.newBtns){ //有新增按钮 imgViewTool.newBtns = options.newBtns } imgViewTool.justShowToggleBtn = !!options.justShowToggleBtn imgViewTool.loading = !(options.loading === false) imgViewTool.title = options.title || false imgViewTool.navbar = !!options.navbar // 是否开启自动轮播 if(options.slideDuration && options.slideDuration > 0) { imgViewTool.slideInfo.autoSlide = true imgViewTool.slideInfo.duration = options.slideDuration } imgViewTool.hasLoaded = true; imgViewTool.needEdit = needEdit; imgViewTool.initHtml(); if (!imgViewTool.needEdit) { //不需要图片编辑 $('#imgtoolWrap #imgEdit').hide(); } else { //点确定后,编辑页是替换原图,详情页是复制 if (window.location.href.indexOf('noteRichtext') > -1 || options.type == 'edit') { //编辑页 $('#imgtoolWrap #imgReplace').show(); // $('#imgtoolWrap #imgCopy').hide(); } else {//详情页 $('#imgtoolWrap #imgReplace').hide(); $('#imgtoolWrap #imgCopy').show(); } imgViewTool.getUploadConfig(); //获取上传需要的puid和云盘Token } if (options.showAppArrow) { $('#imgtoolWrap').addClass('showArrow') } imgViewTool.loadFiles(); imgViewTool.initEvent(); } /*初始化 * params container:需要查看大图的容器 * params originurl:存大图src的属性,可传‘data-original',默认不传的时候是'src' * params index:图片在容器中的索引值,不传为0 */ imgViewTool.initViewImage = function (container, originurl, index,json) { var ua = navigator.userAgent.toLowerCase(); if (ua && ua.indexOf("chaoxingstudy") != -1 && ua.indexOf('_pc_') == -1 && window.self == window.top && typeof jsBridge == 'object') { var imgArray = new Array(); $(container).find('img').each(function () { var imgObj = {"imageUrl": $(this).attr(originurl || 'src')}; imgArray.push(imgObj); }) jsBridge.postNotification('CLIENT_PREVIEW_IMAGES', { imageUrls: imgArray, showIndex: index }); return; } if(imgViewTool.isOpen){ return; } imgViewTool.isOpen = true; if(window.obj && window.obj.mirrorDomain && (window.obj.mirrorDomain.isMirrorDeploy || window.obj.mirrorDomain.isMirrorDeploy == false && window.obj.mirrorDomain.NoteDomain.indexOf('chaoxing.com') == -1)){ $('#imgtoolWrap #imgReport,#imgtoolWrap #imgForward,#imgtoolWrap #imgSaveCloud,#imgtoolWrap #imgDownload').remove(); } if(json){ if(json.replaceFn){ imgViewTool.replaceFn = json.replaceFn } if(json.needEdit){ imgViewTool.needEdit = json.needEdit; imgViewTool.loadEditFile() $('body').append('
'); imgViewTool.getUploadConfig() $('#imgtoolWrap #imgEdit').show(); imgViewTool.imgEditEvent(); } if(json.hideItems && json.hideItems.length > 0){ json.hideItems.forEach(function (item){ $('#imgtoolWrap #img' + item).remove() }) } } if (!(imgViewTool.puid && imgViewTool.yunToken)) { $('#imgtoolWrap #imgEdit').remove(); } //如果传过来的container是body,显示替换原图,隐藏复制 if (imgViewTool.needEdit && container.getAttribute('contenteditable') && container.getAttribute('contenteditable') == 'true') { $('#imgtoolWrap #imgReplace').show(); // $('#imgtoolWrap #imgCopy').hide(); }else{ $('#imgtoolWrap #imgReplace').hide(); $('#imgtoolWrap #imgCopy').show(); } originurl = originurl || 'src'; imgViewTool.imageViewer = new Viewer(container, { url: originurl, navbar: imgViewTool.navbar, loading: imgViewTool.loading, title: imgViewTool.title, container: document.body, toolbar: false, filter: function (image) { if (image.getAttribute(originurl)) { return true; } else { return false; } }, show: function () { if (typeof (imgViewTool) != 'undefined') { imgViewTool.imgshown(); } }, shown: function() { imgViewTool.slideInfo.openSlide() }, viewed: function () { if (typeof (imgViewTool) != 'undefined') { clearTimeout(imgViewTool.moveTimer); imgViewTool.imgviewed(); // 工具栏打开后1秒内没有操作,隐藏工具栏 imgViewTool.moveTimer = setTimeout(function (){ $('#imgtoolWrap').fadeOut(200) },800) } }, hidden:function () { if(json && json.hiddenFn){ json.hiddenFn() } imgViewTool.slideInfo.closeSlide(); } }); index = index || 0; imgViewTool.imageViewer.index = index; imgViewTool.imageViewer.show(); if (typeof (imgViewTool) == 'undefined') { imgViewTool.unactiveViewBtn(); } $('#imgtoolWrap').fadeIn(); } //事件 imgViewTool.initEvent = function () { //点击阴影 $('body').on('click', '.viewer-container', function (e) { e.stopPropagation(); if($('#imgtoolWrap')[0] && $('#imgtoolWrap')[0].style.opacity) return // 点击缩略图时 不销毁 if(imgViewTool.imageViewer && !e.target.closest('.viewer-navbar')){ imgViewTool.imageViewer.destroy(); imgViewTool.slideInfo.closeSlide(); } if($(e.target).hasClass('viewer-close')){ if (typeof sendMessageFadeInOrOut == 'function') { // 课程那边图片的额外操作 sendMessageFadeInOrOut(0) } } $('#imgtoolWrap').fadeOut(); imgViewTool.closeEditMode(); imgViewTool.isOpen = false; }); $('body').on('click', '.viewer-canvas img,.tui-image-editor-canvas-container', function (e) { e.stopPropagation(); }); //上一个 $('#imgPrev').click(function () { imgViewTool.closeEditMode(); imgViewTool.imageViewer.prev(); imgViewTool.unactiveViewBtn() }) //下一个 $('#imgNext').click(function () { imgViewTool.closeEditMode(); imgViewTool.imageViewer.next(); imgViewTool.unactiveViewBtn() }) //放大 $('#imgZoomIn').click(function () { imgViewTool.imageViewer.zoom(0.1); $('#imgZoomNum').text(parseInt(imgViewTool.imageViewer.imageData.ratio * 100) + '%'); }); //缩小 $('#imgZoomOut').click(function () { imgViewTool.imageViewer.zoom(-0.1); $('#imgZoomNum').text(parseInt(imgViewTool.imageViewer.imageData.ratio * 100) + '%'); }) //1:1 $('#img1-1').click(function () { imgViewTool.imageViewer.zoomTo(1); $('#imgFit').removeClass('hide'); $(this).addClass('hide'); $('#imgZoomNum').text(parseInt(imgViewTool.imageViewer.imageData.ratio * 100) + '%'); }) //适应屏幕 $('#imgFit').click(function () { imgViewTool.imageViewer.reset(); $('#img1-1').removeClass('hide'); $(this).addClass('hide'); $('#imgZoomNum').text(parseInt(imgViewTool.imageViewer.imageData.ratio * 100) + '%'); }) //旋转 $('#imgRotate').click(function () { $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); if ($('#imgtoolWrap').hasClass('editMode')) { //编辑图片的旋转 imgViewTool.imageEditor.rotate(-90); } else { imgViewTool.imageViewer.rotate(-90); } }) //下载 $('#imgDownload').click(function () { if (!$('#imgtoolWrap').hasClass('editMode')) { if ($('.viewer-canvas img')[0]) { var src = $('.viewer-canvas img')[0].getAttribute('src'); if (src) { var oldobjectId = src.substring(src.lastIndexOf("/") + 1, src.lastIndexOf(".")); //需要加图片水印的 if(typeof RichTextUitl != 'undefined' && RichTextUitl.watermarkOptions && RichTextUitl.generateWatermark){ oldobjectId = RichTextUitl.generateWatermark(oldobjectId, RichTextUitl.watermarkOptions) || objectid; } if (oldobjectId) { //获取云存储下载地址 YunFileUtil.downloadYunFile('', oldobjectId); } } } } else { //编辑后的图片 imgViewTool.uploadImg(imgViewTool.downloadImg); } }) // 举报 $('#imgReport').click(function () { if ($('.viewer-canvas img')[0]) { var src = $('.viewer-canvas img')[0].getAttribute('src'); if (src) { var objectId = src.substring(src.lastIndexOf("/") + 1, src.lastIndexOf(".")); if (objectId) { var params = new Array(); params.push({'name': 'type', 'value': 'image'}); params.push({'name': 'sourceIdstr', 'value': $.md5(objectId)}); params.push({'name': 'sourceContent', 'value': encodeURIComponent(JSON.stringify({'image': src}))}); FORM_post(window.location.protocol + '//'+ imgViewTool.getHost(imgViewTool.groupwebDomain) +'/pc/report/reportIndex', params, '_blank'); } } } }) if (imgViewTool.needEdit) { imgViewTool.imgEditEvent(); } //最后一张图片右键头不可点,第一张图片左箭头不可点 $(window).keydown(function (event) { if (imgViewTool.imageViewer) { if (event.keyCode == 27) { imgViewTool.imageViewer.destroy(); $('#imgtoolWrap').fadeOut(); imgViewTool.closeEditMode(); imgViewTool.slideInfo.closeSlide(); imgViewTool.isOpen = false; } else if (event.keyCode == 37) { //左 imgViewTool.unactiveViewBtn(); } else if (event.keyCode == 39) { //右 imgViewTool.unactiveViewBtn(); } } }); $('#imgtoolWrap').on('click mousemove', function (e){ e.stopPropagation() clearTimeout(imgViewTool.moveTimer); }) //停留1秒没有任何操作时隐藏工具栏 $('body').on('mousemove click wheel', '.viewer-canvas', function (){ clearTimeout(imgViewTool.moveTimer); $('#imgtoolWrap').show() //1秒后隐藏工具栏 imgViewTool.moveTimer = setTimeout(function (){ $('#imgtoolWrap').fadeOut() },1000) }) // 编辑按钮点击回调 $('#imgCloseEdit, #imgCopy, #imgForward, #imgReplace, #imgSaveCloud').click(function(){ if (typeof sendMessageFadeInOrOut == 'function') { // 课程那边图片的额外操作 sendMessageFadeInOrOut(0) } }) } //图片编辑事件 imgViewTool.imgEditEvent = function (){ //编辑 $('#imgEdit').click(function () { var src = imgViewTool.imageViewer.images[imgViewTool.imageViewer.index].getAttribute('src') var objectId = src.split('/')[src.split('/').length - 1].split('.')[0] if (!objectId) { return; } var url = document.location.protocol + '//' + imgViewTool.getHost(imgViewTool.noteDomain) + '/pc/files/getImageBase64?objectId=' + objectId; $.ajax({ url: url, type: "get", crossDomain: true, xhrFields: { withCredentials: true }, success: function (res) { var data = res.msg; if (res.result && data.imageData) { imgViewTool.openEditMode(); imgViewTool.imageEditor.loadImageFromURL(data.imageData, 'SampleImage').then(function (sizeValue){ imgViewTool.imageEditor.clearUndoStack(); }); } } }) }) //裁剪 $('#imgCrop').click(function () { imgViewTool.hideSubMenu() $('#imgCancle,#imgApply').removeClass('hide'); $('#imgSure,#imgCancleEdit').addClass('hide'); imgViewTool.imageEditor.startDrawingMode('CROPPER'); // imgViewTool.imageEditor._cropAction().preset('preset-square'); }); //裁剪--应用 $('#imgApply').click(function () { if (imgViewTool.imageEditor.getCropzoneRect()) { imgViewTool.imageEditor.crop(imgViewTool.imageEditor.getCropzoneRect()).then(function () { imgViewTool.imageEditor.stopDrawingMode(); $('.tui-image-editor').height(parseInt($('.tui-image-editor-canvas-container').css('max-height'))); }); } imgViewTool.imageEditor.stopDrawingMode(); $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); }) //裁剪--取消 $('#imgCancle').click(function () { imgViewTool.imageEditor.stopDrawingMode(); $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); }); //矩形 $('#imgDrawRect').click((function () { $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); if (imgViewTool.imageEditor.getDrawingMode() == 'SHAPE' && imgViewTool.shapeType == 'rect') { imgViewTool.hideSubMenu(); $(this).removeClass('active'); } else { imgViewTool.hideSubMenu(); $(this).addClass('active'); $('#editSubMenu .widthList').show(); $('#editSubMenu .fontWrap').hide(); if(imgViewTool.useColor === ""){ $('#editSubMenu.colorList.color').removeClass('active'); $('#editSubMenu.colorList.color:nth-child(1)').addClass('active'); } $('#editSubMenu').css('left', $(this)[0].offsetLeft + $(this).width() - $('#editSubMenu').width() / 2).show(); imgViewTool.shapeOptions.stroke = $('#editSubMenu .colorList p.active').css('background-color'); imgViewTool.shapeOptions.strokeWidth = $('#editSubMenu .widthList p.active').width(); imgViewTool.imageEditor.setDrawingShape('rect', imgViewTool.shapeOptions); imgViewTool.shapeType = 'rect'; imgViewTool.activateShapeMode(); } })) //圆形 $('#imgDrawCircle').click((function () { $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); if (imgViewTool.imageEditor.getDrawingMode() == 'SHAPE' && imgViewTool.shapeType == 'circle') { imgViewTool.hideSubMenu(); $(this).removeClass('active'); } else { imgViewTool.hideSubMenu(); $(this).addClass('active'); $('#editSubMenu .widthList').show(); $('#editSubMenu .fontWrap').hide(); if(imgViewTool.useColor === ""){ $('#editSubMenu.colorList.color').removeClass('active'); $('#editSubMenu.colorList.color:nth-child(1)').addClass('active'); } $('#editSubMenu').css('left', $(this)[0].offsetLeft + $(this).width() - $('#editSubMenu').width() / 2).show(); imgViewTool.shapeOptions.stroke = $('#editSubMenu .colorList p.active').css('background-color'); imgViewTool.shapeOptions.strokeWidth = $('#editSubMenu .widthList p.active').width(); imgViewTool.imageEditor.setDrawingShape('circle', imgViewTool.shapeOptions); imgViewTool.shapeType = 'circle'; imgViewTool.activateShapeMode(); } })) //画笔 $('#imgDrawLine').click((function () { $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); if (imgViewTool.imageEditor.getDrawingMode() == 'FREE_DRAWING') { imgViewTool.hideSubMenu(); $(this).removeClass('active'); } else { imgViewTool.hideSubMenu(); $(this).addClass('active'); $('#editSubMenu .widthList').show(); $('#editSubMenu .fontWrap').hide(); if(imgViewTool.useColor === ""){ $('#editSubMenu.colorList.color').removeClass('active'); $('#editSubMenu.colorList.color:nth-child(1)').addClass('active'); } $('#editSubMenu').css('left', $(this)[0].offsetLeft + $(this).width() - $('#editSubMenu').width() / 2).show(); var settings = { width: $('#editSubMenu .widthList p.active').width(), color: $('#editSubMenu .colorList p.active').css('background-color') }; imgViewTool.imageEditor.stopDrawingMode(); imgViewTool.imageEditor.startDrawingMode('FREE_DRAWING', settings); } })) //文字 $('#imgDrawText').click((function () { $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); if (imgViewTool.imageEditor.getDrawingMode() == 'TEXT') { $(this).removeClass('active'); imgViewTool.hideSubMenu(); } else { imgViewTool.hideSubMenu(); $(this).addClass('active'); $('#editSubMenu .widthList').hide(); $('#editSubMenu .fontWrap').show(); if(imgViewTool.useColor === ""){ $('#editSubMenu.colorList.color').removeClass('active'); $('#editSubMenu.colorList.color:nth-child(1)').addClass('active'); } $('#editSubMenu .fontList p').eq(2).click(); $('#editSubMenu').css('left', $(this)[0].offsetLeft + $(this).width() - $('#editSubMenu').width() / 2).show(); imgViewTool.imageEditor.startDrawingMode('TEXT'); } })); //设置颜色 $('#editSubMenu .colorList p').click(function () { $(this).siblings().removeClass('active'); $(this).addClass('active'); var color = $(this).css('background-color'); if (imgViewTool.useColor === "") { imgViewTool.useColor = color } if (imgViewTool.imageEditor.getDrawingMode() == 'TEXT') { imgViewTool.imageEditor.changeTextStyle(imgViewTool.activeObjectId, { 'fill': color, }); // imgViewTool.imageEditor.stopDrawingMode(); // imgViewTool.imageEditor.startDrawingMode('TEXT'); } else if (imgViewTool.imageEditor.getDrawingMode() == 'FREE_DRAWING') { imgViewTool.imageEditor.setBrush({ color: color }); } else if (imgViewTool.imageEditor.getDrawingMode() == 'SHAPE') { imgViewTool.imageEditor.changeShape(imgViewTool.activeObjectId, { stroke: color }); imgViewTool.shapeOptions.stroke = color; imgViewTool.imageEditor.setDrawingShape(imgViewTool.shapeType, imgViewTool.shapeOptions); imgViewTool.imageEditor.stopDrawingMode(); imgViewTool.imageEditor.startDrawingMode('SHAPE'); } }); //设置宽度 $('#editSubMenu .widthList p').click(function () { $(this).siblings().removeClass('active'); $(this).addClass('active'); var width = $(this).width(); if (imgViewTool.imageEditor.getDrawingMode() == 'FREE_DRAWING') { imgViewTool.imageEditor.setBrush({ width: width }); } else if (imgViewTool.imageEditor.getDrawingMode() == 'SHAPE') { imgViewTool.imageEditor.changeShape(imgViewTool.activeObjectId, { strokeWidth: width }); imgViewTool.shapeOptions.strokeWidth = width; imgViewTool.imageEditor.setDrawingShape('rect', imgViewTool.shapeOptions); imgViewTool.imageEditor.stopDrawingMode(); imgViewTool.imageEditor.startDrawingMode('SHAPE'); } }); //打开字号列表 $('#editSubMenu .fontText').click(function () { $('#editSubMenu .fontList').slideToggle(300); $(this).find('i').toggleClass('down'); }); //设置字号 $('#editSubMenu .fontList p').click(function () { $(this).siblings().removeClass('active'); $(this).addClass('active'); $('#editSubMenu .fontList').hide(); $('#fontSize').html($(this).html()); imgViewTool.imageEditor.changeTextStyle(imgViewTool.activeObjectId, { fontSize: parseInt($(this).html().replace('px', ''), 10), }); // imgViewTool.imageEditor.stopDrawingMode(); // imgViewTool.imageEditor.startDrawingMode('TEXT'); }); //撤回 $('#imgUndo').click((function () { $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); imgViewTool.hideSubMenu() if (!$(this).hasClass('disabled')) { imgViewTool.imageEditor.undo(); } })) //恢复 $('#imgRedo').click((function () { $('#imgCancle,#imgApply').addClass('hide'); $('#imgSure,#imgCancleEdit').removeClass('hide'); imgViewTool.hideSubMenu() if (!$(this).hasClass('disabled')) { imgViewTool.imageEditor.redo(); } })) //确定 $('#imgSure').click((function () { $('#imgtoolWrap .surePop').show(); imgViewTool.uploadImg() })) //取消 $('#imgCancleEdit').click(function () { imgViewTool.closeEditMode(); }) //确定-关闭 $('#imgtoolWrap .surePop p').click(function (e) { e.stopPropagation(); imgViewTool.imageViewer.destroy(); $('#imgtoolWrap').fadeOut(); imgViewTool.closeEditMode(); imgViewTool.slideInfo.closeSlide(); imgViewTool.isOpen = false; }); //复制 $('#imgtoolWrap #imgCopy').click(function (e) { e.stopPropagation(); if (!imgViewTool.previewUrl) { var timer = setInterval(function () { if (imgViewTool.previewUrl) { clearInterval(timer); imgViewTool.copyImg() } }, 1000) } else { imgViewTool.copyImg() } }); //转发 $('#imgtoolWrap #imgForward').click(function (e) { e.stopPropagation(); var ua = navigator.userAgent; var isPhone = (!!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1) if ( !isPhone && typeof (ForwardUtils) == 'undefined') { imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.shareDomain) + '/res/plugin/forword/js/forward.js', "js",function () { if (!imgViewTool.previewUrl) { var timer = setInterval(function () { if (imgViewTool.previewUrl) { clearInterval(timer); imgViewTool.forwardImg() } }, 1000) } else { imgViewTool.forwardImg() } }); }else if(!isPhone){ if (!imgViewTool.previewUrl) { var timer = setInterval(function () { if (imgViewTool.previewUrl) { clearInterval(timer); imgViewTool.forwardImg() } }, 1000) } else { imgViewTool.forwardImg() } } }); //保存到云盘 $('#imgtoolWrap #imgSaveCloud').click(function (e) { e.stopPropagation(); if (!imgViewTool.previewUrl) { var timer = setInterval(function () { if (imgViewTool.previewUrl) { clearInterval(timer); imgViewTool.saveCloudImg() } }, 1000) } else { imgViewTool.saveCloudImg() } }); //替换原图 $('#imgtoolWrap #imgReplace').click(function (e) { e.stopPropagation(); $('.edui-editor-imagescale').removeClass('hover').removeClass('scale') if (!imgViewTool.previewUrl) { var timer = setInterval(function () { if (imgViewTool.previewUrl) { clearInterval(timer); imgViewTool.replaceImg() } }, 1000) } else { imgViewTool.replaceImg() } }); //关闭编辑模式 $('#imgCloseEdit').click(function () { imgViewTool.closeEditMode(); imgViewTool.imageViewer.destroy(); $('#imgtoolWrap').hide(); imgViewTool.slideInfo.closeSlide(); imgViewTool.isOpen = false; }) } //替换原图 imgViewTool.replaceImg = function () { var index = imgViewTool.imageViewer.index; var img = imgViewTool.imageViewer.images[index]; var newsrc = imgViewTool.previewUrl; // 新图片地址 var newObjectid = imgViewTool.objectId; //新图片objectId img.setAttribute('src', newsrc); img.setAttribute('_src', newsrc); img.setAttribute('objectid', newObjectid); img.onload = function () { var params = this.src.split('?'); var src = ''; if (params.length > 1 && (params[1].indexOf('rw=') == -1 || params[1].indexOf('rh=') == -1)) { src = this.getAttribute('src') + '&rw=' + this.naturalWidth + '&rh=' + this.naturalHeight; } else if (params.length == 0 && (params[1].indexOf('rw=') == -1 || params[1].indexOf('rh=') == -1)) { src = this.getAttribute('src') + '?rw=' + this.naturalWidth + '&rh=' + this.naturalHeight; } if(imgViewTool.replaceFn){ imgViewTool.replaceFn(img,src); } this.setAttribute('_src', src) //裁剪后图片如果有高度会发生变形 if (this.style.width && parseInt(this.style.width.replace('px', '')) && this.style.height && parseInt(this.style.height.replace('px', ''))) { var originWidth = parseInt(this.style.width.replace('px', '')); var originHeight = parseInt(this.style.height.replace('px', '')); var newHeight = parseInt((this.naturalHeight * originWidth) / this.naturalWidth); if (newHeight > originHeight) { //新高度大于原高度,高度保持不变,宽度变小 this.style.width = parseInt(this.naturalWidth * originHeight / this.naturalHeight) + 'px' } else { //新高度小于原始高度,宽度保持不变,高度变小 this.style.height = newHeight + 'px' } this.removeAttribute('height', ''); } } } ////复制图片 imgViewTool.copyImg = function () { var dt = new clipboard.DT(); dt.setData("text/html", ''); clipboard.write(dt).then(function () { if ($('.toolTipBox').length > 0) { $('.toolTipBox').remove() } $(document.body).append('') $('.toolTipBox').show(); setTimeout(function () { $('.toolTipBox').fadeOut(); }, 1500) }, function (err) { console.log(err); }); } //转发图片 imgViewTool.forwardImg = function () { var imgUrl = imgViewTool.previewUrl + '?rw=' + imgViewTool.imageEditor.getCanvasSize().width + '&rh=' + imgViewTool.imageEditor.getCanvasSize().height + '&_fileSize=' + imgViewTool.size; var attachment = { type: 'img', title: imgViewTool.imgTitle, url: imgUrl, objectId: imgViewTool.objectId, file: imgViewTool.file, }; ForwardUtils.forward(attachment); } //图片保存到云盘 imgViewTool.saveCloudImg = function () { var imgSrc = imgViewTool.previewUrl; var objectid = imgViewTool.getObjectIdByImgSrc(imgSrc); if (!objectid) { return; } var src = imgSrc; var name = ''; if (src.indexOf('?') > -1) { name = src.substring(src.lastIndexOf('/') + 1, src.indexOf('?')) } else { name = src.substring(src.lastIndexOf('/') + 1); } var obj = { objectId: objectid, title: name, type:'img' } if(typeof ForwardUtils == 'undefined') return ForwardUtils.saveTo({ 'data': obj, 'type':'cloud', 'fileType':'img' }) } //初始化编辑对象 imgViewTool.initImageEditor = function () { if(typeof tui.ImageEditor == "undefined"){ return } imgViewTool.imageEditor = new tui.ImageEditor('.tui-image-editor', { cssMaxWidth: $(window).width() * 0.9, cssMaxHeight: $(window).height() * 0.9, selectionStyle: { cornerStyle: 'circle', cornerSize: 16, cornerColor: '#FFFFFF', lineWidth: 8, cornerStrokeColor: '#FF0000', rotatingPointOffset: 70 } }); imgViewTool.imageEditor.on({ objectAdded: function (objectProps) { console.info(objectProps); }, undoStackChanged: function (length) { if (length) { $('#imgUndo').removeClass('disabled'); } else { $('#imgUndo').addClass('disabled'); } $('.tui-image-editor').height(parseInt($('.tui-image-editor-canvas-container').css('max-height'))); }, redoStackChanged: function (length) { if (length) { $('#imgRedo').removeClass('disabled'); } else { $('#imgRedo').addClass('disabled'); } $('.tui-image-editor').height(parseInt($('.tui-image-editor-canvas-container').css('max-height'))); }, objectScaled: function (obj) { if (obj.type === 'text') { $inputFontSizeRange.val(obj.fontSize); } }, addText: function (pos) { imgViewTool.imageEditor.addText('双击输入文字', { position: pos.originPosition, styles: { fontSize: 24, fill: $('#editSubMenu .colorList p.active').css('background-color') }, }).then(function(objectProps) { console.log(objectProps); }); }, objectActivated: function (obj) { imgViewTool.activeObjectId = obj.id; if (obj.type === 'text') { imgViewTool.activateTextMode(); } }, mousedown: function (event, originPointer) { } }); } /*初始化工具栏*/ imgViewTool.initHtml = function () { var html = ''; if (imgViewTool.needEdit) { html += '
'; } // 隐藏工具栏 只显示切换图片按钮 if(imgViewTool.justShowToggleBtn) { html = ''; } $('body').append(html); if(imgViewTool.newBtns){ html = ''; for(var i = 0;i < imgViewTool.newBtns.length;i++){ var item = imgViewTool.newBtns[i] html = '
'+item.hoverText+'
' $('#imgtoolWrap').append(html); $('#imgtoolWrap').find('#'+item.btnId).on('click',function () { for(var i = 0;i < imgViewTool.newBtns.length;i++) { if($(this).attr('id') == imgViewTool.newBtns[i].btnId){ imgViewTool.newBtns[i].clickFn() } } }) } } } //下载图片 imgViewTool.downloadImg = function () { if (imgViewTool.objectId) { //获取云存储下载地址 YunFileUtil.downloadYunFile('', imgViewTool.objectId); } } //打开编辑模式 imgViewTool.openEditMode = function () { $('#imgtoolWrap').addClass('editMode'); $('.viewer-canvas').hide(); $('#imageEditContainer').show(); $('#imgEdit').hide(); } //关闭编辑模式 imgViewTool.closeEditMode = function () { $('#imgtoolWrap').removeClass('editMode'); $('.viewer-canvas').show(); //显示图片大图,避免再次查看不显示 $('#imageEditContainer').hide(); //图片编辑容器 imgViewTool.hideSubMenu(); $('#imgEdit').css('display', 'inline-block'); } //编辑--关闭子级菜单 imgViewTool.hideSubMenu = function () { $('.imgEditBtns .imgbtn').removeClass('active'); if (imgViewTool.imageEditor) { imgViewTool.imageEditor.stopDrawingMode(); } $('#editSubMenu').hide(); //子菜单--选择字体颜色粗细 $('#imgCancle,#imgApply').addClass('hide'); //裁剪取消 应用 $('#imgtoolWrap .surePop').hide(); //确定弹窗 imgViewTool.shapeType = ''; } //编辑--打开文本模式 imgViewTool.activateTextMode = function () { if (imgViewTool.imageEditor.getDrawingMode() !== 'TEXT') { imgViewTool.imageEditor.stopDrawingMode(); imgViewTool.imageEditor.startDrawingMode('TEXT'); } } //编辑--打开图像模式 imgViewTool.activateShapeMode = function () { if (imgViewTool.imageEditor.getDrawingMode() !== 'SHAPE') { imgViewTool.imageEditor.stopDrawingMode(); imgViewTool.imageEditor.startDrawingMode('SHAPE'); } } //编辑--获取画笔设置 imgViewTool.getBrushSettings = function () { var brushWidth = $('#editSubMenu .widthList p.active').width(); var brushColor = $('#editSubMenu .colorList p.active').css('background-color'); return { width: brushWidth, color: imgViewTool.hexToRGBa(brushColor, 1) }; } // HEX to RGBA imgViewTool.hexToRGBa = function (hex, alpha) { var r = parseInt(hex.slice(1, 3), 16); var g = parseInt(hex.slice(3, 5), 16); var b = parseInt(hex.slice(5, 7), 16); var a = alpha || 1; return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')'; } imgViewTool.uploadImg = function (callback) { //上传图片 imgViewTool.previewUrl = ''; imgViewTool.imgTitle = ''; imgViewTool.size = ''; imgViewTool.objectId = ''; // var imageName = imgViewTool.imageEditor.getImageName(); var imageName = (new Date()).getTime() + ".png"; var dataURL = imgViewTool.imageEditor.toDataURL(); //base64 if (!!(window.File && window.FileList && window.FileReader)) { var blob = imgViewTool.base64ToBlob(dataURL); // console.log(blob); imgViewTool.file = imgViewTool.blobToFile(blob, imageName); var formData = new FormData(); formData.append('file', imgViewTool.file, imageName); formData.append("puid", imgViewTool.puid); formData.append("_token", imgViewTool.yunToken); var url = window.location.protocol + '//' + imgViewTool.getHost(imgViewTool.panDomain) + '/upload'; $.ajax({ type: "post", url: url, async: true, cache: false, data: formData, dataType: "json", processData: false, //不对参数进行转换序列号 contentType: false, //fromData上传文件时将其设置为false success: function (res) { if (res.result) { imgViewTool.previewUrl = res.data.previewUrl + '?_fileSize=' + res.data.size + '&_orientation=1'; imgViewTool.imgTitle = res.data.name; imgViewTool.size = res.data.size; imgViewTool.objectId = res.data.objectId; if (callback) { callback(); } } } }); } } //将blob转换为file imgViewTool.blobToFile = function (theBlob, fileName) { theBlob.lastModifiedDate = new Date(); theBlob.name = fileName; return theBlob; } //base64转blob imgViewTool.base64ToBlob = function (data) { var mimeString = ''; var raw, uInt8Array, i, rawLength; raw = data.replace(/data:(image\/.+);base64,/, function (header, imageType) { mimeString = imageType; return ''; }); raw = atob(raw); rawLength = raw.length; uInt8Array = new Uint8Array(rawLength); // eslint-disable-line for (i = 0; i < rawLength; i += 1) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], {type: mimeString}); } //更新左右切换按钮状态 imgViewTool.unactiveViewBtn = function () { if (imgViewTool.imageViewer) { $('#imgPrev').removeClass('disabled'); $('#imgNext').removeClass('disabled'); if (imgViewTool.imageViewer.index == 0) { $('#imgPrev').addClass('disabled'); } if (imgViewTool.imageViewer.index == (imgViewTool.imageViewer.length - 1)) { $('#imgNext').addClass('disabled'); } if (imgViewTool.imageViewer.length == 1) { $('#imgpage').addClass('hide'); } else { $('#imgpage').removeClass('hide'); } $('#nowImgIndex').html(imgViewTool.imageViewer.index + 1); $('#imgFit').addClass('hide'); $('#img1-1').removeClass('hide'); } } //查看大图显示时调用 imgViewTool.imgshown = function () { $('#nowImgIndex').html(imgViewTool.imageViewer.index + 1); $('#imgTotalNum').html(imgViewTool.imageViewer.length); var img = null; if(!imgViewTool.imageViewer.images) return; if(imgViewTool.imageViewer.images.length > 0 && imgViewTool.imageViewer.index < imgViewTool.imageViewer.images.length){ img = imgViewTool.imageViewer.images[imgViewTool.imageViewer.index]; } if(!img) return if ($(img).hasClass('noSelect') || (img.getAttribute('download') && img.getAttribute('download') == 'false')) { $('#viewDownload,#imgDownload,#imgEdit').hide(); } imgViewTool.unactiveViewBtn(); if (img.getAttribute('src').indexOf('.gif') > -1) { $('#imgEdit').hide(); } } //图片大图加载出来时调用 imgViewTool.imgviewed = function () { $('#nowImgIndex').html(imgViewTool.imageViewer.index + 1); $('#imgTotalNum').html(imgViewTool.imageViewer.length); $('#imgZoomNum').html(parseInt(imgViewTool.imageViewer.imageData.ratio * 100) + '%'); if(!imgViewTool.imageViewer.images || imgViewTool.imageViewer.images.length <= imgViewTool.imageViewer.index){ return } var img = imgViewTool.imageViewer.images[imgViewTool.imageViewer.index]; if ($(img).hasClass('noSelect') || (img.getAttribute('download') && img.getAttribute('download') == 'false')) { $('#viewDownload,#imgDownload,#imgEdit').hide(); $('.viewer-canvas img').addClass('noSelect').on('contextmenu', function () { return false; }); } else { $('#viewDownload,#imgDownload').css('display', ''); if (imgViewTool.needEdit) { $('#imgEdit').css('display', 'inline-block'); } $('.viewer-canvas img').removeClass('noSelect').off('contextmenu'); } if (img.getAttribute('src').indexOf('.gif') > -1) { $('#imgEdit').hide(); } } //加载需要的js和css imgViewTool.loadFiles = function () { imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + '/res/plugin/viewer/css/viewer.css', "css"); if (typeof (Viewer) == 'undefined') { imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + '/res/plugin/viewer/js/viewer.js', "js"); } imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + '/res/plugin/viewer/css/viewer-button.css', "css"); //编辑图片需要加载的js if (imgViewTool.needEdit) { imgViewTool.loadEditFile() } imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + "/res/plugin/viewer/js/jquery.md5.js", "js"); if(typeof YunFileUtil == 'undefined'){ imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + "/res/js/common/yun.file.util.js", "js") } } imgViewTool.loadEditFile = function(){ try{ imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + '/res/plugin/viewer/js/tui-image-editor-3.15.3.min.js', "js", function () { if (typeof tui != "undefined") { imgViewTool.initImageEditor(); } else { imgViewTool.needEdit = false; $('#imgtoolWrap #imgEdit').remove(); } }); if (typeof (clipboard) == 'undefined') { imgViewTool.loadExtentFile("//" + imgViewTool.getHost(imgViewTool.noteDomain) + '/res/plugin/ueditor/third-party/clipboard-polyfill.promise.js', "js"); } }catch (e) { console.log(e) } } //加载外部js、css地址、回调函数 imgViewTool.loadExtentFile = function (filePath, fileType, fCallback) { if (fileType == "js") { var oJs = document.createElement('script'); oJs.setAttribute("type", "text/javascript"); oJs.setAttribute("src", filePath);//文件的地址 ,可为绝对及相对路径 document.getElementsByTagName("head")[0].appendChild(oJs);//绑定 if (/msie/.test(window.navigator.userAgent.toLowerCase())) { oJs.onreadystatechange = function () { if (this.readyState == "loaded" || this.readyState == "complete") { if (fCallback) fCallback(); } }; } else if (/gecko/.test(window.navigator.userAgent.toLowerCase())) { oJs.onload = function () { if (fCallback) fCallback(); }; } else { if (fCallback) fCallback(); } } else if (fileType == "css") { var oCss = document.createElement("link"); oCss.setAttribute("rel", "stylesheet"); oCss.setAttribute("type", "text/css"); oCss.setAttribute("href", filePath); document.getElementsByTagName("head")[0].appendChild(oCss);//绑定 } } /** * 根据图片地址获取 objectId * @param imgSrc * @returns {string|*} */ imgViewTool.getObjectIdByImgSrc = function (imgSrc) { if (!imgSrc) { return ''; } var objectId = ''; if (imgSrc.indexOf(".") > -1) { objectId = imgSrc.substring(imgSrc.lastIndexOf("/") + 1, imgSrc.lastIndexOf(".")); } else { // 部分图片可能没有后缀 objectId = imgSrc.substring(imgSrc.lastIndexOf("/") + 1); } return objectId; } /** * 获取上传相关配置 * @param sync 是否同步调用, true 同步,false 异步 */ imgViewTool.getUploadConfig = function (sync) { var json = { url: window.location.protocol + "//" + imgViewTool.getHost(imgViewTool.noteDomain) + "/pc/files/getUploadConfig", type: "get", xhrFields: { withCredentials: true }, async:false, headers: {"Content-Type": "application/x-www-form-urlencoded"}, data: {}, dataType: "json", success: function (resultData) { if (resultData && resultData.result == 1) { imgViewTool.puid = resultData.msg.puid; imgViewTool.yunToken = resultData.msg.token || ''; } else { $('#imgEdit').remove(); } }, error: function () { $('#imgEdit').remove(); } } if (sync) { // 同步调用 json.async = false; } $.ajax(json); } /** * 截取域名,去掉协议 http:// 和 https:// * 例: http://noteyd.chaoxing.com -> noteyd.chaoxing.com */ imgViewTool.getHost = function (url) { if (!url) { return '' } if (url.indexOf('http:') == 0 || url.indexOf('https:') == 0) { return url.substring(url.indexOf('://') + 3); } //增加默认不走镜像域名情况下去除 // if (url.indexOf('//') == 0) { return url.substring(url.indexOf('//') + 2); } return url; } // 自动轮播相关配置 imgViewTool.slideInfo = { autoSlide: false, // 是否需要自动轮播 默认不需要 duration: 3000, // 自动轮播时间间隔 slideTimer: null, // 定时器 openSlide: function(){ if(!this.autoSlide) { return } // console.log('开启轮播') this.slideTimer = setInterval(function() { imgViewTool.imageViewer.next(true) }, this.duration) }, closeSlide: function(){ if(!this.autoSlide || !this.slideTimer) { return } // console.log('关闭轮播'); clearInterval(this.slideTimer) this.slideTimer = null }, } var FORM_post = function(url, params,target){ if(!url || !target){ return ; } var form = document.createElement("form"); form.action = url; form.method ="post"; form.target = target; if(params){ for(var i in params){ var ele = document.createElement("textarea"); ele.name = params[i].name; ele.value = params[i].value; form.appendChild(ele); } } document.body.appendChild(form); form.submit(); // 移除 document.body.removeChild(form); }