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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay