Categories
Mastering Development

State access between main js and js script loaded from html

I am building a paint app using html canvas. Also I am using menu buttons to change active color, shapes and to switch fill option. So all my logic lives in canvas.js file imported in index.html, where I manage canvas, but my current settings live in index.js. But I can’t find a way to speak between index.js and this script file. Now every time I start to draw – I send a IPC request to main file and get back current settings, but that is not fast enough method. Ideally I need to already have my current settings ready in this canvas.js file by the time I start to draw something. What is the best way to do it?

index.js:

const { app, BrowserWindow, Menu, ipcMain } = require('electron');

let win;

let color = '#ffff00';
let shape = 'PointShape';
let fill = true;

...
  win.loadFile('index.html');
...

ipcMain.on('getSettings', (event) => {
  event.reply('letSettings', color, shape, fill);
});

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Electron Paint App</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script src="canvas.js"></script>
  </body>
</html>

cansav.js:

window.addEventListener('load', () => {
    require('events').defaultMaxListeners = 9999;
    const { ipcRenderer } = require('electron');

...

function startPosition(e) {
        ipcRenderer.send('getSettings');
        ipcRenderer.on('letSettings', (event, color, shape, fill) => {
            curColor = color;
            curShape = shape;
            curFill = fill;
        });

...

window.global.canvas.addEventListener("mousedown", startPosition);

Leave a Reply

Your email address will not be published. Required fields are marked *