If we draw a triangle and a fill triangle using wireframe mode and fill mode

            let canvas = document.getElementById('canvas');
            let ctx = canvas.getContext('2d');
            // Wireframes
            ctx.moveTo(20.20);
            ctx.lineTo(100.100);
            ctx.lineTo(100.0);
            // The stroke color is determined by strokeStyle
            ctx.strokeStyle = '#0000FF';
            // Stroke the line segment or curve in the current path
            ctx.stroke();
            // Fill mode
            ctx.moveTo(120.20);
            ctx.lineTo(200.100);
            ctx.lineTo(200.0);
            ctx.fillStyle = 'pink';
            ctx.fill();
Copy the code

The result is as follows

But we notice that the first part is also filled in because there can only be one path in the canvas, This is called “current path”. When a path is traced or filled with fill() or stroke(), all lines and curves of the path are traced or filled with the specified color, even if the path is broken.

[But we don't want the first rectangle to be filled, what should we do? We can use ctx.beginPath(); (url)

            let canvas = document.getElementById('canvas');
            let ctx = canvas.getContext('2d');
            ctx.moveTo(20.20);
            ctx.lineTo(100.100);
            ctx.lineTo(100.0);
            ctx.strokeStyle = '#0000FF';
            ctx.stroke();
            ctx.beginPath();
            ctx.moveTo(120.20);
            ctx.lineTo(200.100);
            ctx.lineTo(200.0);
            ctx.fillStyle = 'pink';
            ctx.fill();
Copy the code

The beginPath() method starts a path, or resets the current path.