1. 思路:
1.1 通过canvas生成一块画布,在画布上绘制图形
let videoEl = document.getElementById("testVideo");
let params = {
videoEl,
quality:0.95
}
let canvasEl = document.createElement('canvas');
canvasEl.width = videoEl.width;
canvasEl.height = videoEl.height;
let ctx = canvasEl.getContext('2d');
ctx.drawImage(videoEl, 0, 0, canvasEl.width, canvasEl.height);
const base64Url = canvasEl.toDataURL('image/jpeg', quality);
let fileName = 'test.jpg'
1.2 利用node.js 的fs.writeFile方法保存图片到本地
fs.writeFile(file,data,callback)
file 文件名或文件描述
data 写入的数据
callback 回调函数
2.代码片段
2.1 js
async screenshotFn(){
let videoEl = document.getElementById("testVideo");
let params = {
videoEl,
quality:0.95
}
let canvasEl = document.createElement('canvas');
canvasEl.width = videoEl.width;
canvasEl.height = videoEl.height;
let ctx = canvasEl.getContext('2d');
ctx.drawImage(videoEl, 0, 0, canvasEl.width, canvasEl.height);
const base64Url = canvasEl.toDataURL('image/jpeg', quality);
let fileName = 'test.jpg'
//下面是调用node.js 的fs.writeFile方法保存图片到本地
await window.ipcApis.saveFile({ fileName: fileName, data: base64Url });
}
2.2 electron/ipcModule/ipcMain.js
const { ipcMain, app, clipboard } = require("electron");
const path = require("path")
const fs = require("fs");
const os = require('os');
import logger from "@/utils/log"
import { store } from "@/utils/store";
// 注册主进程通信
function registerIpcMainMsgModule(win) {
saveFile(),
setStore(),
getStore()
}
function saveFile() {
ipcMain.on("save-file", (event, params) => {
let { fileName, data } = params;
const dir = store.get("systemPath");
const buffer = Buffer.from(data.replace(/^.*base64,/, ""), 'base64');
fs.writeFile(path.join(dir, fileName), buffer, (err) => {
logger.error(err);
if(err){
event.returnValue = false;
}
event.returnValue = true;
});
})
}
// 设置store
function setStore() {
ipcMain.handle("set-store", (event, item) => {
store.set(item.key, item.val)
})
}
// 获取store
function getStore() {
ipcMain.handle("get-store", (event, key) => {
return store.get(key)
})
}
export {
registerIpcMainMsgModule,
}