'JavaScript externe class or array visible into onmessage worker
With p5.js in a first time I cannot draw gradually the Koch snowflake: when a click to perform I see the result of the drawing when the recursion is gone.
so I implemented it with worker thread
As I don't know how to share external var like a class or an array (because if a create a type="module" script it is not ok with the worker.js)
I can arrived to do it with difficulty
'Koch snowflake' is made in recursive mode.
The project is
- index.html
- main.js
- worker.js that contain (onmessage = function... , and the VonKoch class)
in worker.js it's like
onmessage = function(e) {
console.log('Worker: Message received from main script');
let depth = e.data.depth;
let f = new VonKoch(VonKoch);
};
class VonKoch {
constructor(depth) {
...
}
pencil_advance(){
...
postMessage([this.x, this.y, this.x + dx, this.y + dy, ]);
Surprising ! it can send message from/into the class which is out of onmessage
}
...
}
From the main.js it is like:
function setup() {
noLoop();
createCanvas(800, 400);
if (window.Worker) {
const myWorker = new Worker("worker.js");
let el = {profondeur:profondeur};
myWorker.postMessage(el);
let a=0;
a message has been received so with p5.js it draws a line
myWorker.onmessage = (e) => {
line(e.data[0],e.data[1],e.data[2],e.data[3]);
a++;
};
With that I can see the draws gradually.
Ok, but I want more simple and speed result with an external array[][] of pixel that I can redraw every setInterval( ...; redraw(), 500).
The "main.js" can recognize this array if it is declared and initialized in "worker.js" but when this array is modified in "worker.js" (with VonKoch class), the main.js will see the initial array class without modification. Maybe it is come from "new Worker("worker.js")?
And if I create this array class in the "main.js" it won't be recognized in "worker.js".
The only way to have a "array class" that is recognized in "main.js" is to put it in the "worker.js".
Thank you for your help
Solution 1:[1]
Solved.
With localStorage : not ok (see comment) with indexedDB : not ok (see comment)
The solution is : in the "worker.js" that perform Koch snowflake, when it does to draw there is a test of time. If the Date.now() is greater than 500 (ms) i send the matrix with post. So the "main.js" while draw the matrix with p5.js after receiving the message comes from "worker.js". It is fast
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user7058377 |