Spaces:
Running
Running
/** | |
* Main script to call the worker. | |
* The canvas will be transferred to the Worker. | |
* The main script will pass the color and shape to the worker. | |
* The worker will then draw the shape with the color. | |
*/ | |
const color = document.querySelector("#color"); | |
const shape = document.querySelector("#shape"); | |
// Use getElementById: No need to append the # in front of the id | |
const drawingArea = document.getElementById("drawingArea"); | |
// offscreen canvas for worker | |
const offscreen = drawingArea.transferControlToOffscreen(); | |
// Check if the window has Worker. | |
if (window.Worker) { | |
const worker = new Worker("./worker.js"); | |
// transfer the offscreen to the worker | |
let messageToWorker = { | |
command: "getOffscreen", | |
canvas: offscreen | |
} | |
// The [] array buffer must be transferred to the Worker. | |
worker.postMessage(messageToWorker, [offscreen]); | |
worker.addEventListener("message", messageFromWorker); | |
// get the color and shape to draw | |
color.addEventListener("change", drawShape); | |
shape.addEventListener("change", drawShape); | |
// process message from worker | |
function messageFromWorker(message) { | |
console.log("Main: Message received from worker"); | |
// get the status of work | |
if(message.data.status) { | |
console.log(`Main: Message from worker: ${message.data.result}`); | |
} | |
else { | |
console.log(`Main: Worker cannot complete the status for some reason.`) | |
} | |
} | |
// event listener to draw a shape | |
function drawShape(event) { | |
// initial selection will contain value="", then this to default | |
// lightgrey square. | |
validColor = (color.value!=="" ? color.value : "lightgrey"); | |
validShape = (shape.value!==""? shape.value : "square"); | |
const drawData = { | |
command: "draw", | |
selectedColor: validColor, | |
selectedShape: validShape | |
} | |
worker.postMessage(drawData); | |
worker.addEventListener("message", messageFromWorker); | |
} | |
} else { | |
console.log('Your browser doesn\'t support web workers.'); | |
} | |