热门搜索:软件下载

vue中图片旋转不停止(在vue中嵌入的html代码中图片使用v-viewer实现旋转、放大等功能)

首页教程vue中图片旋转不停止更新时间:2023-06-13 23:43:05
一、前情提要

本文主要实现在vue代码中,将html代码、js代码以及css代码嵌入div中,并使用html代码与vue的通信,实现双击图片,调用vue里面的方法,实现图片的旋转、放大等功能。

二、具体实现1、要嵌入到vue代码中的部分html代码

双击图片会调用imgDbClick方法,此方法为html里面的方法。

<img ondblclick="imgDbClick(this)" src="http:127.0.0.1/test/test.png"> 2、imgDbClick方法

双击图片时会调用此方法,此方法会发起跨域通信。

/*点击图片触发*/ var imgDbClick = function (img) { window.parent.postMessage({ cmd: 'dealImg', params: { url: img.src, } }, '*'); }; 3、vue中的代码

在下面的div中嵌入html代码

<div id="showHtml"> </div> 4、嵌入html代码

下方代码中的htmlStr为具体的html代码。

let element = document.getElementById(activeName); element.innerHTML = htmlStr; 5、嵌入js代码

因为js代码存在文件服务器上,所以采用文件引入的方式。

//动态绑定script let scriptElement = document.createElement("script"); scriptElement.type = "text/javascript"; scriptElement.src = "http://127.0.0.1/test/common_code/common.js"; element.append(scriptElement); 6、嵌入css代码

css代码存在文件服务器上,所以采用文件引入的方式。

let styleElement = document.createElement("link"); styleElement.rel="stylesheet"; styleElement.type="text/css"; styleElement.href="http://127.0.0.1/test/common_code/common.css"; element.append(styleElement); 7、监听html的通信

监听message,拿到图片的地址,并使用viewer来实现旋转、放大等功能

window.addEventListener('message',(event)=>{ const res = event.data; if(res.cmd =='dealImg'){ let url =res.params.url; //需要引入其它文件,见8、9、10 this.$viewerApi({ images: [url] }) } }) 8、使用v-viewer

使用npm命令安装v-viewer

npm install v-viewer 9、全局引用

在main.js中全局引用

import 'viewerjs/dist/viewer.css' import { api as viewerApi } from "v-viewer" Vue.prototype.$viewerApi = viewerApi; 10、使用

imagesArr为url数组,在需要使用的地方调用即可

this.$viewerApi({ images: imagesArr }) 三、实现效果

,