DEV Community 👩‍💻👨‍💻

Jess F
Jess F

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

Top comments (0)

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!