File size: 2,013 Bytes
4840bff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * 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);
    }
}