liewchooichin's picture
Upload 4 files
4840bff verified
/**
* First, the Worker will get the offscreenCanvas.
* On changes to selection, Worker will take the color and shape
* and draw on the canvas.
*/
let offscreenCanvas;
let ctx;
let workStatus = {
status: false,
result: ""
};
// The message will be handled in this function.
onmessage = drawShape;
function drawShape(message) {
console.log('Worker: Message received from main script');
console.log(`Worker: command ${message.data.command}`)
// get the offscreen canvas
if(message.data.command==="getOffscreen") {
offscreenCanvas = message.data.canvas;
ctx = offscreenCanvas.getContext("2d");
console.log(`Worker: canvas (w x h): (${offscreenCanvas.width}, ${offscreenCanvas.height}).`);
// return a message to indicate the offscreen is successful
workStatus.status = true;
workStatus.result = "Worker: Got the offscreen canvas.";
postMessage(workStatus);
}
// get the color and shape
if(message.data.command==="draw") {
const color = message.data.selectedColor;
const shape = message.data.selectedShape;
console.log(`Worker: Receive order to draw a ${color} ${shape}.`);
// draw now
// clear the canvas first
ctx.clearRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
ctx.fillStyle = color;
switch(shape) {
case "square":
ctx.fillRect(x=0, y=0, w=100, h=100);
break;
case "rect":
ctx.fillRect(x=0, y=0, w=100, h=60);
break;
case "circle":
ctx.beginPath();
ctx.arc(x=60, y=60, radius=50,
startAngle=0, endAngle=2*Math.PI);
ctx.fill();
break;
}
// return a message to indicate it has finished drawing
workStatus.status = true;
workStatus.result = "Worker: Finish drawing the shape.";
postMessage(workStatus);
}
}