DEV Community

Jess
Jess

Posted on

Complex Shapes Part B (something I forgot to mention previously)

I want to add a quick addition to my previous post where I discussed creating a shape from a series of line segments like this:

ctx.lineWidth = 3; // just making it a little more visible
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.lineTo(100,100);
ctx.lineTo(20,200);
ctx.lineTo(100,200);
ctx.lineTo(200, 20);
ctx.lineTo(200, 200);
ctx.stroke();
Enter fullscreen mode Exit fullscreen mode

A line zig-zagging in different directions

I forgot to mention that there is a way to write this using a 2 dimensional array so you don't have to repeat so much.

// set your points in a 2d array
const shape = [
    [20,20],
    [20,100],
    [100, 100],
    [20, 200],
    [100, 200],
    [200, 20],
    [200, 200]
];

ctx.lineWidth = 3;
ctx.beginPath();

// loop through each set of points
// if it's the first set (at index 0), `moveTo` that point,
// otherwise use `lineTo`
shape.forEach((p, i) => { 
  i === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1])
})

ctx.stroke();
Enter fullscreen mode Exit fullscreen mode

Discussion (0)