UNPKG

hevue-img-preview

Version:

> 本组件是一个基于 vue 编写的 vue 图片预览组件,支持 pc 和手机端,支持单图和多图预览,仅传入一个图片地址,即可实现图片预览效果。手机端支持单指拖拽和双指缩放。页面各组件颜色均可可自定义,实现个性化设计,如果能帮上你,希望可以移步 [GitHub](https://github.com/heyongsheng/hevue-img-preview) ,或者[码云](https://gitee.com/ihope_top/hevue-img-preview) 给个小星星,如果有任何使用意见或建议

2 lines (1 loc) 18.1 kB
(function(u,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],g):(u=typeof globalThis<"u"?globalThis:u||self,g(u.hevueImgPreview={},u.Vue))})(this,function(u,g){"use strict";function x(e){const i=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,s.get?s:{enumerable:!0,get:()=>e[t]})}}return i.default=e,Object.freeze(i)}const I=x(g);var b=function(){var e=this,i=e.$createElement,t=e._self._c||i;return e.visible?t("div",{ref:"heImg",staticClass:"hevue-imgpreview-wrap",attrs:{id:"hevue-imgpreview-wrap"},on:{mouseup:function(s){return e.removeMove("pc")},touchend:function(s){return e.removeMove("mobile")}}},[t("div",{staticClass:"hevue-img-mask",class:{heShow:e.showTranstion},on:{click:function(s){return s.stopPropagation(),e.clickMask.apply(null,arguments)}}}),t("div",{staticClass:"he-img-wrap",class:{heShow:e.showTranstion}},[t("div",{directives:[{name:"show",rawName:"v-show",value:e.imgState===1,expression:"imgState === 1"}],staticClass:"heimgfont hevue-img-status-icon rotate-animation"},[e._v("  ")]),e.vueVersion>2?t("transition-group",{attrs:{name:"fade"}},e._l(e.needLoadImg,function(s){return t("img",{directives:[{name:"show",rawName:"v-show",value:e.imgState===2&&e.imgIndex==s.index,expression:"imgState === 2 && imgIndex == item.index"}],key:s.index,ref:"heImg"+s.index,refInFor:!0,staticClass:"he-img-view",style:[e.imgIndex,e.fromIndex].includes(s.index)?e.getImgPostion:e.maxWH,attrs:{src:s.url},on:{click:function(n){n.stopPropagation()},contextmenu:e.imgContextMenu,mousedown:e.addMove,touchstart:e.addMoveMobile}})}),0):e._l(e.needLoadImg,function(s){return t("img",{directives:[{name:"show",rawName:"v-show",value:e.imgState===2&&e.imgIndex==s.index,expression:"imgState === 2 && imgIndex == item.index"}],key:s.index,ref:"heImg"+s.index,refInFor:!0,staticClass:"he-img-view",style:[e.imgIndex,e.fromIndex].includes(s.index)?e.getImgPostion:e.maxWH,attrs:{src:s.url},on:{click:function(n){n.stopPropagation()},contextmenu:e.imgContextMenu,mousedown:e.addMove,touchstart:e.addMoveMobile}})}),t("div",{directives:[{name:"show",rawName:"v-show",value:e.imgState===3,expression:"imgState === 3"}],staticClass:"heimgfont hevue-img-status-icon"},[e._v("  ")]),e.closeBtn?t("div",{staticClass:"heimgfont he-close-icon theme-item",on:{click:function(s){return s.stopPropagation(),e.close({way:"closeBtn"})}}},[t("span",[e._v("")])]):e._e(),e.arrowBtn&&e.multiple?t("div",{staticClass:"arrow arrow-left heimgfont theme-item",on:{click:function(s){return s.stopPropagation(),e.prevNextHandle(!1,"arrow-btn")}}},[t("span",[e._v("")])]):e._e(),e.arrowBtn&&e.multiple?t("div",{staticClass:"arrow arrow-right heimgfont theme-item",on:{click:function(s){return s.stopPropagation(),e.prevNextHandle(!0,"arrow-btn")}}},[t("span",[e._v("")])]):e._e(),t("div",{staticClass:"he-bottom-wrap"},[t("transition",{attrs:{name:"fade"}},[t("div",{directives:[{name:"show",rawName:"v-show",value:e.showHevueImgRotate,expression:"showHevueImgRotate"}],staticClass:"hevue-custom-rotate-wrap"},[t("span",{staticClass:"hevue-custom-range-label theme-item"},[t("span",[e._v(e._s(e.imgRotate)+"°")])]),t("input",{directives:[{name:"model",rawName:"v-model.number",value:e.imgRotate,expression:"imgRotate",modifiers:{number:!0}}],staticClass:"hevue-custom-range theme-item",attrs:{type:"range",id:"vol",min:"0",max:"360",orient:"vertical"},domProps:{value:e.imgRotate},on:{__r:function(s){e.imgRotate=e._n(s.target.value)},blur:function(s){return e.$forceUpdate()}}})])]),e.controlBar.length?t("div",{staticClass:"he-control-bar theme-item",on:{click:function(s){s.stopPropagation()}}},e._l(e.controlbarShowItems,function(s,n){return t("div",{directives:[{name:"show",rawName:"v-show",value:s.show(),expression:"item.show()"}],key:n,staticClass:"he-control-btn heimgfont",attrs:{title:e.controlbarI18n[e.locale][s.title]},domProps:{innerHTML:e._s(s.icon)},on:{click:function(o){return o.stopPropagation(),s.handle()}}})}),0):e._e(),e.thumbnail&&e.multiple?t("div",{staticClass:"he-imglist-wrap"},[t("div",{staticClass:"he-imglist",style:{left:e.getThumbLeft()+"px"}},e._l(e.imgList,function(s,n){return t("div",{key:n,staticClass:"he-img-item",class:{active:n==e.imgIndex},on:{click:function(o){return e.toogleImg(n,"thumb")}}},[t("img",{staticClass:"he-img-item-img",attrs:{src:s},on:{contextmenu:e.imgContextMenu}})])}),0)]):e._e(),e.controlBar.length&&e.multiple?t("div",{staticClass:"he-control-num theme-item"},[t("span",[e._v(e._s(e.imgIndex+1)+" / "+e._s(e.imgList.length))])]):e._e()],1),t("transition",{attrs:{name:"fade"}},[t("div",{directives:[{name:"show",rawName:"v-show",value:e.showHevueImgHelp,expression:"showHevueImgHelp"}],staticClass:"hevue-img-help-wrap theme-item"},e._l(e.shortcutList,function(s){return t("div",{key:s.keyName,staticClass:"hevue-img-help-item"},[t("div",{staticClass:"hevue-img-help-item-label"},[e._v(e._s(s.keyName)+":")]),t("div",{staticClass:"hevue-img-help-item-desc"},[e._v(" "+e._s(e.shortI18n[e.locale][s.desc])+" ")])])}),0)])],2),t("svg",{staticStyle:{display:"none"}},[t("filter",{attrs:{id:"glass-distortion",x:"0%",y:"0%",width:"100%",height:"100%",filterUnits:"objectBoundingBox"}},[t("feTurbulence",{attrs:{type:"fractalNoise",baseFrequency:"0.01 0.01",numOctaves:"1",seed:"5",result:"turbulence"}}),t("feComponentTransfer",{attrs:{in:"turbulence",result:"mapped"}},[t("feFuncR",{attrs:{type:"gamma",amplitude:"1",exponent:"10",offset:"0.5"}}),t("feFuncG",{attrs:{type:"gamma",amplitude:"0",exponent:"1",offset:"0"}}),t("feFuncB",{attrs:{type:"gamma",amplitude:"0",exponent:"1",offset:"0.5"}})],1),t("feGaussianBlur",{attrs:{in:"turbulence",stdDeviation:"3",result:"softMap"}}),t("feSpecularLighting",{attrs:{in:"softMap",surfaceScale:"5",specularConstant:"1",specularExponent:"100","lighting-color":"white",result:"specLight"}},[t("fePointLight",{attrs:{x:"-200",y:"-200",z:"300"}})],1),t("feComposite",{attrs:{in:"specLight",operator:"arithmetic",k1:"0",k2:"1",k3:"1",k4:"0",result:"litImage"}}),t("feDisplacementMap",{attrs:{in:"SourceGraphic",in2:"softMap",scale:"150",xChannelSelector:"R",yChannelSelector:"G"}})],1)])]):e._e()},_=[];const H="";function C(e,i,t,s,n,o,h,m){var a=typeof e=="function"?e.options:e;i&&(a.render=i,a.staticRenderFns=t,a._compiled=!0),s&&(a.functional=!0),o&&(a._scopeId="data-v-"+o);var r;if(h?(r=function(c){c=c||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,!c&&typeof __VUE_SSR_CONTEXT__<"u"&&(c=__VUE_SSR_CONTEXT__),n&&n.call(this,c),c&&c._registeredComponents&&c._registeredComponents.add(h)},a._ssrRegister=r):n&&(r=m?function(){n.call(this,(a.functional?this.parent:this).$root.$options.shadowRoot)}:n),r)if(a.functional){a._injectStyles=r;var d=a.render;a.render=function(p,f){return r.call(f),d(p,f)}}else{var l=a.beforeCreate;a.beforeCreate=l?[].concat(l,r):[r]}return{exports:e,options:a}}const N={name:"hevue-img-preview",data(){return{vue:I,showHevueImgRotate:!1,visible:!1,imgScale:1,imgTop:0,imgLeft:0,imgRotate:0,isFull:!1,maxWH:{"max-width":"100%","max-height":"100%"},clientX:0,clientY:0,imgIndex:0,canRun:!0,imgurl:"",imgState:1,start:[{},{}],fromIndex:0,mobileScale:0,imgList:[],nowImgIndex:0,thumbnail:!0,controlBar:[],closeBtn:!0,arrowBtn:!0,keyboard:!0,clickMaskCLose:!0,closeFn:null,changeFn:null,customStyle:{},themeName:"glass",disabledImgRightClick:!1,showTranstion:!1,needLoadImg:[],showHevueImgHelp:!1,locale:"zhCN",shortI18n:{zhCN:{key27:"退出预览",key65:"上一张",key68:"下一张",key87:"放大",key83:"缩小",key37:"上一张",key39:"下一张",key38:"放大",key40:"缩小",key81:"逆时针旋转",key69:"顺时针旋转",key82:"重置旋转"},en:{key27:"Exit preview",key65:"Previous",key68:"Next",key87:"Zoom in",key83:"Zoom out",key37:"Previous",key39:"Next",key38:"Zoom in",key40:"Zoom out",key81:"Rotate counterclockwise",key69:"Rotate clockwise",key82:"Reset rotation"}},shortcutList:[{keyNum:27,keyName:"Esc",desc:"key27",handle:()=>{this.close({way:"esc"})}},{keyNum:65,keyName:"A",desc:"key65",handle:()=>{this.multiple&&this.prevNextHandle(!1,"key-a")}},{keyNum:68,keyName:"D",desc:"key68",handle:()=>{this.multiple&&this.prevNextHandle(!0,"key-d")}},{keyNum:87,keyName:"W",desc:"key87",handle:()=>{this.scaleFunc(.15)}},{keyNum:83,keyName:"S",desc:"key83",handle:()=>{this.scaleFunc(-.15)}},{keyNum:37,keyName:"←",desc:"key37",handle:()=>{this.multiple&&this.prevNextHandle(!1,"key-left")}},{keyNum:39,keyName:"→",desc:"key39",handle:()=>{this.multiple&&this.prevNextHandle(!0,"key-right")}},{keyNum:38,keyName:"↑",desc:"key38",handle:()=>{this.scaleFunc(.15)}},{keyNum:40,keyName:"↓",desc:"key40",handle:()=>{this.scaleFunc(-.15)}},{keyNum:81,keyName:"Q",desc:"key81",handle:()=>{this.rotateFunc(-90)}},{keyNum:69,keyName:"E",desc:"key69",handle:()=>{this.rotateFunc(90)}},{keyNum:82,keyName:"R",desc:"key82",handle:()=>{this.initImg()}}],controlbarI18n:{zhCN:{zoomOut:"缩小",zoomIn:"放大",rotateLeft:"向左旋转",customRotate:"自定义旋转",rotateRight:"向右旋转",reset:"复位",prev:"上一个",next:"下一个",download:"下载",help:"帮助"},en:{zoomOut:"Zoom Out",zoomIn:"Zoom In",rotateLeft:"Rotate Left",customRotate:"Custom Rotate",rotateRight:"Rotate Right",reset:"Reset",prev:"Prev",next:"Next",download:"Download",help:"Help"}},controlbarAllItems:[{key:"zoomOut",icon:"&#xe65e;",title:"zoomOut",show:()=>!0,handle:()=>{this.scaleFunc(-.15)}},{key:"zoomIn",icon:"&#xe65d;",title:"zoomIn",show:()=>!0,handle:()=>{this.scaleFunc(.15)}},{key:"rotateLeft",icon:"&#xe662;",title:"rotateLeft",show:()=>!0,handle:()=>{this.rotateFunc(-90)}},{key:"customRotate",icon:"&#xe927;",title:"customRotate",show:()=>!0,handle:()=>{this.showHevueImgRotate=!this.showHevueImgRotate}},{key:"rotateRight",icon:"&#xe663;",title:"rotateRight",show:()=>!0,handle:()=>{this.rotateFunc(90)}},{key:"reset",icon:"&#xe86b;",title:"reset",show:()=>!0,handle:()=>{this.initImg()}},{key:"prev",icon:"&#xe62f;",title:"prev",show:()=>()=>this.multiple,handle:()=>{this.prevNextHandle(!1,"control-bar")}},{key:"next",icon:"&#xe62e;",title:"next",show:()=>()=>this.multiple,handle:()=>{this.prevNextHandle(!0,"control-bar")}},{key:"download",icon:"&#xe694;",title:"download",show:()=>!0,handle:()=>{this.downloadIamge()}},{key:"help",icon:"&#xe626;",title:"help",show:()=>this.keyboard,handle:()=>{this.showHevueImgHelp=!this.showHevueImgHelp}}]}},created(){},mounted(){this.initImg()},computed:{vueVersion(){return parseInt(this.vue.version)},controlbarShowItems(){return this.controlBar.map(e=>this.controlbarAllItems.find(t=>t.key===e))},multiple(){return Array.isArray(this.imgList)&&this.imgList.length>1},getImgPostion(){return{...this.maxWH,transform:`scale(${this.imgScale}) rotate(${this.imgRotate}deg)`,marginTop:this.imgTop+"px",marginLeft:this.imgLeft+"px"}}},watch:{customStyle:{handler(e){let i=Object.entries(e);this.$nextTick(()=>{i.length>0&&i.forEach(t=>{let s=t[0],n=t[1],o=document.querySelector(".hevue-imgpreview-wrap");o&&o.style.setProperty(s,n)})})},immediate:!0,deep:!0},url(){this.initImg()},visible:{handler(e){e&&this.$nextTick(()=>{let i=document.getElementById("hevue-imgpreview-wrap");i.onmousewheel=this.scrollFunc,document.body.addEventListener("DOMMouseScroll",this.scrollFunc),document.ondragstart=function(){return!1},this.themeName&&i.classList.add(this.themeName),this.disableTransition&&i.classList.add("disableTransition"),Array.isArray(this.controlBar)?this.controlBar.length===0&&(this.controlBar=this.controlbarAllItems.map(t=>t.key)):this.controlBar=[],this.url&&(!this.imgList||this.imgList.length===0)&&(this.imgList=[this.url]),this.imgIndex=Number(this.nowImgIndex)||0,this.changeUrl(this.imgList[this.imgIndex],this.imgIndex),this.keyboard&&document.addEventListener("keydown",this.keyHandleDebounce)})},immediate:!0}},methods:{show(){this.visible=!0,setTimeout(()=>{this.showTranstion=!0},20)},close(e){this.showTranstion=!1,setTimeout(()=>{this.initImg(),document.body.removeEventListener("DOMMouseScroll",this.scrollFunc),document.ondragstart=null,this.keyboard&&document.removeEventListener("keydown",this.keyHandleDebounce),this.visible=!1,this.closeFn&&this.closeFn(e),this.showHevueImgHelp=!1,this.imgList=[]},500)},initImg(){this.mobileScale=1,this.imgScale=1,this.imgRotate=0,this.imgTop=0,this.imgLeft=0},imgContextMenu(e){e=e||window.event,this.disabledImgRightClick&&e.preventDefault()},prevNextHandle(e,i){let t=0;e?(t=this.imgIndex+1,t>this.imgList.length-1&&(t=0)):(t=this.imgIndex-1,t<0&&(t=this.imgList.length-1)),this.toogleImg(t,i,e)},toogleImg(e,i,t){if(this.imgIndex===e)return;this.fromIndex=this.imgIndex;let s=this.imgIndex;this.imgIndex=e;let n=i=="thumb"?"thumb":t?"next":"prev";this.changeFn&&this.changeFn({type:n,fromImgIndex:s,fromImgUrl:this.imgList[s],toImgIndex:this.imgIndex,toImgUrl:this.imgList[this.imgIndex],way:i}),this.changeUrl(this.imgList[this.imgIndex],this.imgIndex)},changeUrl(e,i){this.needLoadImg.find(s=>s.index==i)?this.imgState=2:(this.imgState=1,this.needLoadImg.push({url:e,index:i}),this.$nextTick(()=>{let s=this.$refs["heImg"+i][0];s.onload=()=>{i!=null&&i==this.imgIndex?this.imgState=2:i==null&&(this.imgState=2)},s.onerror=()=>{i!=null&&i==this.imgIndex?this.imgState=3:i==null&&(this.imgState=3)}}))},getThumbLeft(){return-(this.imgIndex*100+50)},rotateFunc(e){let i=+this.imgRotate+e;i>360?i=i-360:i<0&&(i=360+i),this.imgRotate=i},scaleFunc(e,i){this.imgScale<=.2&&e<0||(i?this.imgScale=e:this.imgScale+=e)},imgToggle(){this.initImg(),this.isFull?this.maxWH={"max-width":"100%","max-height":"100%"}:this.maxWH="",this.isFull=!this.isFull},scrollFunc(e){e=e||window.event,e.delta=e.wheelDelta||-e.detail,e.preventDefault(),e.delta>0&&this.scaleFunc(.05),e.delta<0&&this.scaleFunc(-.05)},addMove(e){e=e||window.event,this.clientX=e.clientX,this.clientY=e.clientY,this.$refs.heImg.onmousemove=this.moveFunc},addMoveMobile(e){e.preventDefault(),e=e||window.event,e.touches.length>1?this.start=e.touches:(this.clientX=e.touches[0].pageX,this.clientY=e.touches[0].pageY),this.$refs.heImg.ontouchmove=this.moveFuncMobile},moveFunc(e){e=e||window.event,e.preventDefault();let i=e.clientX-this.clientX,t=e.clientY-this.clientY;this.imgLeft+=i*2,this.imgTop+=t*2,this.clientX=e.clientX,this.clientY=e.clientY},moveFuncMobile(e){if(e=e||window.event,e.touches.length>1){var i=e.touches,t=this.getDistance(i[0],i[1])/this.getDistance(this.start[0],this.start[1]);this.mobileScale?t>1?this.scaleFunc(t+this.mobileScale-1,!0):this.scaleFunc(t*this.mobileScale,!0):this.scaleFunc(t,!0)}else{let s=e.touches[0];e.preventDefault();let n=s.pageX-this.clientX,o=s.pageY-this.clientY;this.imgLeft+=n*2,this.imgTop+=o*2,this.clientX=s.pageX,this.clientY=s.pageY}},removeMove(e){e==="pc"?this.$refs.heImg.onmousemove=null:(this.mobileScale=this.imgScale,this.$refs.heImg.ontouchmove=null)},keyHandleDebounce(e){this.canRun&&(this.keyHandle(e),this.canRun=!1,setTimeout(()=>{this.canRun=!0},100))},keyHandle(e){e=window.event||e;var i=e.keyCode||e.which||e.charCode;let t=this.shortcutList.find(s=>s.keyNum===i);t&&t.handle()},clickMask(){this.clickMaskCLose&&this.close({way:"mask"})},getDistance(e,i){var t=i.pageX-e.pageX,s=i.pageY-e.pageY;return Math.sqrt(t*t+s*s)},downloadIamge(){let e=new Image;e.setAttribute("crossOrigin","anonymous"),e.onload=function(){let i=document.createElement("canvas");i.width=e.width,i.height=e.height,i.getContext("2d").drawImage(e,0,0,e.width,e.height);let s=i.toDataURL("image/png"),n=document.createElement("a"),o=new MouseEvent("click");n.download="photo"+ +new Date,n.href=s,n.dispatchEvent(o)},e.onerror=function(i){console.log("图片信息不正确或图片服务器禁止访问"),console.log(i)},e.src=this.imgList[this.imgIndex]},isValidColor(e,i,t,s){if(s<128)return!1;const n=(e+i+t)/3;return!(n>240||n<15)},getDominantColorWithFilter(e){const i=document.createElement("canvas"),t=i.getContext("2d"),s=100,n=Math.min(s/e.naturalWidth,s/e.naturalHeight,1);i.width=e.width*n,i.height=e.height*n,t.drawImage(e,0,0);const h=t.getImageData(0,0,i.width,i.height).data,m={};let a=0,r="";for(let l=0;l<h.length;l+=4){const c=h[l],p=h[l+1],f=h[l+2],M=h[l+3];if(!this.isValidColor(c,p,f,M))continue;const v=`${c},${p},${f}`;m[v]=(m[v]||0)+1,m[v]>a&&(a=m[v],r=v)}const d=document.querySelector(".hevue-imgpreview-wrap.glass");return d.style.setProperty("--hevueimg-main-text-color",`rgb(${r}, .7)`),d.style.setProperty("--hevueimg-main-text-color",`rgb(${r}, .5)`),r},rgbToHsl(e,i,t){e/=255,i/=255,t/=255;const s=Math.max(e,i,t),n=Math.min(e,i,t);let o,h,m=(s+n)/2;if(s===n)o=h=0;else{const a=s-n;switch(h=m>.5?a/(2-s-n):a/(s+n),s){case e:o=(i-t)/a+(i<t?6:0);break;case i:o=(t-e)/a+2;break;case t:o=(e-i)/a+4;break}o/=6}return[o*360,h,m]},hslToRgb(e,i,t){e/=360;let s,n,o;if(i===0)s=n=o=t;else{const h=(r,d,l)=>(l<0&&(l+=1),l>1&&(l-=1),l<.16666666666666666?r+(d-r)*6*l:l<.5?d:l<.6666666666666666?r+(d-r)*(.6666666666666666-l)*6:r),m=t<.5?t*(1+i):t+i-t*i,a=2*t-m;s=h(a,m,e+1/3),n=h(a,m,e),o=h(a,m,e-1/3)}return[Math.round(s*255),Math.round(n*255),Math.round(o*255)]},adjustColor(e,i=.5){const[t,s]=this.rgbToHsl(...e);return this.hslToRgb(t,s,i)}}},w={};var L=C(N,b,_,!1,S,"f2fc101e",null,null);function S(e){for(let i in w)this[i]=w[i]}const R=function(){return L.exports}();let y={};function k(e){typeof e=="string"?e={imgList:[e]}:Array.isArray(e)&&(e={imgList:e}),Object.keys(y).forEach(o=>{e[o]===void 0&&(e[o]=y[o])});const i=document.getElementById("hevue-img-preview-container");i&&i.remove();const t=document.createElement("div");t.id="hevue-img-preview-container",t.style.zIndex=e.zIndex||"9999",document.body.appendChild(t);const s=g.extend(R),n=new s({data:e});return n.$mount(t),document.body.appendChild(t),n.show(),n}const F={install(e,i={}){y=i,e.prototype.$hevueImgPreview=k}};u.default=F,u.previewImages=k,Object.defineProperties(u,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});