/* 使用.vue */
<template>
<img :src="newSrc" ref="img" />
</template>
<script>
import { isSupport, copyImgUrl, copyImg } from "@/utils/electronEx";
export default {
name: "electronImgCopy",
computed: {
newSrc(){
return src;
}
},
props: {
src: {},
},
mounted() {
this.isWin = isSupport();
this.$emit("ready", this.isWin);
},
methods: {
async copy() {
if (!this.isWin) {
return false;
}
const img = this.$refs["img"];
debugger;
await copyImg(img);
// await copyImgUrl(this.newSrc);
return true;
},
/**
* 获取是否可以复制
*/
isCopy() {
return this.isWin;
},
},
data() {
return {
isWin: false,
};
},
};
</script>
<style scoped lang="scss">
</style>
// electronEx.js
/**
* 检查是否在,或者是否支持 electron
*/
export const isSupport = function () {
return !!window.isWin;
}
/**
* 传入已经加载好图片的img元素,将其复制到剪切板
* @param {Image ,img 元素的图片复制到剪切板中} base64Image
*/
export const copyImg = function (imgElement, outputFormat) {
return new Promise(async (resolve) => {
let canvasEl = document.createElement('CANVAS'),
ctx = canvasEl.getContext('2d');
canvasEl.height = imgElement.naturalHeight;
canvasEl.width = imgElement.naturalWidth;
imgElement.setAttribute('crossOrigin', 'anonymous');
ctx.drawImage(imgElement, 0, 0);
var base64Image = canvasEl.toDataURL(outputFormat || 'image/png');
canvasEl = null;
yxWin.copyImgBase64(base64Image);
resolve(true);
})
}
以上是远程的vue项目页面代码
下面是electron中的代码
// preload.js
/**
* 将base64图片,拷贝到剪切板上
* @param {base64格式的图片} base64Image
*/
const copyImgBase64 = function (base64Image) {
const image = require('electron').nativeImage.createFromDataURL(base64Image)
require('electron').clipboard.writeImage(image);
}
// 将公开的方法都放入到yxWin下面吗
window.isWin = true;
window.yxWin = {
copyImgBase64
}
// main.js
//下面是部分代码,主要注意这三个配置即可nodeIntegration、contextIsolation、enableRemoteModule
// 以及记得加载preload
mainWindow = new BrowserWindow({
width: 1366,
height: 768,
webPreferences: {
preload: path.join(__dirname, 'src', 'preload.js'),
// nodeIntegration: true,
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
}
})
======================
上面有一个坑,就是图片存在跨域的话,是需要处理的,不然无法通过canvas转成base64
在完成上面功能的时候也发现还有其他的方法,比如通过ipc提供一个方法转为base64,或者img通过nginx代理或者什么代理,变成同域或者增加允许跨域的相关header
====================
注意版本号:electron 11.1.1
需求:
electron提供sdk给远程web页面达到复制图片的功能,web页面提供一个按钮点击后将图片复制到剪切板用户可以直接黏贴