Equal scaling of the Electron window (zoom in and out according to the width and height)
text
-
Obtain the correct resolution and update the initial size of the BrowserWindow to the correct resolution -
Block the scaling operation of the window, calculate the size of the proportionally scaled window and apply it.
1. Get and set the initial size
const mainWindow = new BrowserWindow({ width: 960, height: 630, // icon:app.getAppPath() + "/favicon.ico", icon:path.join(__dirname,"src/TemplateData", 'favicon.ico'), webPreferences: { Preload: path. jin (__dirname, '/reload. js'),//This item will be automatically injected into the web page at runtime devTools:false, nodeIntegration:true }, show:false, }); mainWindow.loadFile('src/index.html'); mainWindow.once("ready-to-show",()=>{ mainWindow.show(); })
//preload.js const { ipcRenderer} = require('electron'); window.addEventListener("DOMContentLoaded",OnLoadFinish); function OnLoadFinish(){ let realSize = GetRealSize(); ipcRenderer.send("realSize",realSize); } function GetRealSize(){ //Get the DOM, and then get its width and height //Note that if the width and height of the string is 100px, you need to manually change it to Number. let mainContent = document.getElementById("xxx"); let w = mainContent.style.width; let h = mainContent.style.height; if(typeof(w) == "string"){ w = parseInt(w.split("px")[0]); h = parseInt(h.split("px")[0]); } return { width:w, height:h } }
//main.js let realSize = null; ipcMain.once("realSize",(e,args)=>{ realSize = {width:args.width, height:args.height}; mainWindow.setMinimumSize(parseInt((args.width) / 2),parseInt((args.height + 30)/2)); MainWindow. setContentSize (args. width, args. height);//Note that this item sets ContentSize, which does not include the title bar. })
2. Equal scale when zooming
mainWindow.on("will-resize", resizeWindow); function resizeWindow(event, newBounds){ if(realSize == null){ return; } const win = event.sender; event.preventDefault();// Intercept to make the window unchanged first const currentSize = win.getSize(); const widthChanged = (currentSize[0] != NewBounds. width) if(widthChanged){ win.setContentSize(newBounds.width, parseInt(newBounds.width / (realSize.width / realSize.height) + 0.5)); } else { win.setContentSize(parseInt((realSize.width / realSize.height) * newBounds.height + 0.5), newBounds.height); } }
3. Other problems
//preload.js window.addEventListener("resize",onResize); function onResize(){ //Do some other things, such as resizing the div so that it can evenly fill the window }