Electron入门Demo之桌面应用计算器笔记(二)

码文不易啊,转载请带上本文链接呀,感谢感谢 https://www.cnblogs.com/echoyya/p/14307996.html


在之前总结了一篇自学笔记,通过之前学习到的方法和知识,完成了一个较为简单的桌面应用程序,Electron 实现桌面计算器,并打包成 .exe 可执行文件可安装包文件

简要绘制一下该Demo的主要功能

简短描述一下所用到的基础知识

  1. 初始化应用,创建窗口,加载内容

  2. 设置菜单文件,main.js 引入菜单文件

  3. 渲染进程创建子窗口

  4. 渲染进程与主进程之间通讯

  5. 执行用户选择操作,并进行本地缓存,便于下次启动应用时,读取用户设置

  6. 项目文件目录结构

准备工作

  1. 创建一个空的文件夹,并创建入口 main.js 文件,计算器必要文件,计算器的代码,此处就不贴了,已上传至百度云,可自行下载

  2. 安装electron

    • npm init -y:初始化配置文件 package.json

    • npm i electron

  3. 创建文件夹及文件

    • 主进程菜单文件:./main-process/calculatorMenu.js

    • 渲染进程颜色文件:./render-process/calculatorColor.js

main.js:基本构建

// app:控制应用的生命周期   BrowserWindow: 创建浏览器窗口
const { app ,BrowserWindow, ipcMain} = require('electron');

const path = require('path');
  
// 引入设置菜单文件
require('./main-process/calculatorMenu');

app.on('ready',ny_createWindow)

let win;
// 创建窗口
function ny_createWindow(){
  win = new BrowserWindow({
    345,
    height:370,
    webPreferences: {
      nodeIntegration: true,  
      enableRemoteModule: true,  
    }
  });
  // 加载内容
  win.loadURL(path.join(__dirname, './calculator/index.html')) // 计算器

  win.on('close',function(){
    win = null;   // 关闭窗口
    app.quit();  // 关闭应用
  })
}
 

./main-process/calculatorMenu.js

// 1.创建菜单模板
const { Menu, BrowserWindow, app} = require('electron');
const path = require('path');

let template = [{
    label: '计算器',
    submenu: [{
        label: '关于计算器',
        click: function () {
          ny_createAboutWindow()
        }
      },
      {
        label: '退出',
        accelerator: 'ctrl+Q',
        click: function () {
          app.quit();
        }
      }
    ]
  },
  {
    label: '格式',
    submenu: [{
        label: '颜色',
        click: function () {
          ny_createColorWindow()
        }
      },
      {
        type: 'separator'
      },
      {
        label: '字体增大',
        accelerator: 'F11',
        click: function (item,win) {
          // 主进程 - > 渲染进程 通讯
          if(win){
            win.webContents.send('add')  // 不需要发送数据
          }
        }
      },
      {
        label: '字体减小',
        accelerator: 'F12',
        click: function (item,win) {
          if(win){
            win.webContents.send('cut')
          }
        }
      },
      {
        label: '默认字体',
        accelerator: (function () {
          return 'ctrl+0'
        })(),
        click: function (item,win) {
          if(win){
            win.webContents.send('normal')
          }
        }
      }
    ]
  }
]

// 2.构建菜单,实例化一个菜单对象
let menu = Menu.buildFromTemplate(template);

// 3. 把菜单对象设置到应用中
Menu.setApplicationMenu(menu);

// 4.创建 about 窗口
function ny_createAboutWindow() {
  let win = new BrowserWindow({
     284,
    height: 198
  })

  win.loadURL(path.join(__dirname, '../calculator/about.html'));

  // 子窗口不要菜单
  win.setMenu(null)

  win.on('close', function () {
    win = null;
  })
}

//  5.创建 color 窗口
function ny_createColorWindow() {
  let win = new BrowserWindow({
     260,
    height: 95,
    webPreferences: {
      nodeIntegration: true
    }
  });
  win.loadURL(path.join(__dirname, '../calculator/color.html'));

  win.setMenu(null);

  win.on('click', function () {
    win = null;
  })
}

./calculator/color.html

<script>
  require('../render-process/calculatorColor');
</script>

./render-process/calculatorColor.js

// 渲染进程
const {ipcRenderer} = require('electron')

//<li data-color="#00ffff" style="background-color: #00ffff;"></li>
let lis = document.querySelectorAll('li');

// 遍历每个li,绑定点击事件 获取对应的颜色值 this.dataset.color, 发送到主进程
for (let i = 0; i < lis.length; i++) {
  var li = lis[i];
  li.onclick = function(){
    ipcRenderer.send('colorToMain',this.dataset.color)
  }
}

进程之间的通讯,传递颜色值和字体大小变化的指令

  1. color传值:渲染进程 --> 主进程 --> 渲染进程

  2. fontSize传值:主进程 --> 渲染进程

代码补充

main.js:

ipcMain.on('colorToMain',function(event,color){

  win.webContents.send('colorToRender',color);

})

./calculator/index.js

// 获取屏幕input对象
let txt = document.getElementById("txt");

if (localStorage.getItem('color')) {
    txt.style.color = localStorage.getItem('color')
}

if (localStorage.getItem('fontSize')) {
    txt.style.fontSize = localStorage.getItem('fontSize')
}

// 接受 Color
ipcRenderer.on('colorToRender', function (event, color) {
    txt.style.color = color
    localStorage.setItem('color', color)
})

// 字体增大
ipcRenderer.on('add', function (event, data) {
    let fontSize = window.getComputedStyle(txt).fontSize;
    fontSize = parseInt(fontSize) + 3
    txt.style.fontSize = fontSize + 'px'
    localStorage.setItem('fontSize',fontSize + 'px');
});

// 字体减小
ipcRenderer.on('cut', function (event, data) {
    let fontSize = window.getComputedStyle(txt).fontSize;
    fontSize = parseInt(fontSize) - 3;
    txt.style.fontSize = fontSize + 'px';
    localStorage.setItem('fontSize',fontSize + 'px');
})

// 默认字体
ipcRenderer.on('normal', function (event, data) {
    txt.style.fontSize = '30px';
    txt.style.color = '#ffffff';
    localStorage.setItem('fontSize','30px');
    localStorage.setItem('color', '#ffffff')
});

打包为安装包

  • 下载:npm i electron-builder -g

  • electron-builder可以将应用程序打包为安装文件,如.exe .dmg,对于windows系统打包为.exe,对于mac系统打包为.dmg

  • 实现electron-builder的配置,package.json 文件, npm run XXX 执行

    "build":{
      "appId":"com.test.app",
      "productName":"calculator",
      "dmg":{
        "icon":"./images/mac.icns",
        "window":{
          "x":200,
          "y":150,
          "width":540,
          "height":380
          }
        },
        "mac": {
        	"icon":"./images/mac.icns"
        },
        "win":{
        	"icon":"./src/img/win.ico"
        }
    },
    "scripts": {
      "start": "electorn .", 
      "buildwin":"electron-builder --win ",
      "buildwin":"electron-builder --mac ",
      "packager":"electron-packager ./ calculator --platform=win32 --out=./dist --arch=x64 --app-version=1.0.1 --ignore=node_modules --icon=./src/img/win.ico --overwrite ",
    }
    

前情提要:Electron小白入门自学笔记(一)

上述为应用全部源码,欢迎指教共同学习~~~!

作者:Echoyya
著作权归作者和博客园共有,商业转载请联系作者获得授权,非商业转载请注明出处。
原文地址:https://www.cnblogs.com/echoyya/p/14307996.html