Categories
JavaScript Answers

How to draw smooth curve through N points using JavaScript HTML5 canvas?

Spread the love

Sometimes, we want to draw smooth curve through N points using JavaScript HTML5 canvas.

In this article, we’ll look at how to draw smooth curve through N points using JavaScript HTML5 canvas.

How to draw smooth curve through N points using JavaScript HTML5 canvas?

To draw smooth curve through N points using JavaScript HTML5 canvas, we create a loop that calls the canvas context quandraticCurveTo method with the end and midpoints.

For instance, we write

const points = [
  { x: 1, y: 1 },
  { x: 2, y: 3 },
  { x: 3, y: 4 },
  { x: 4, y: 2 },
  { x: 5, y: 6 },
];
ctx.moveTo(points[0].x, points[0].y);

for (let i = 0; i < points.length - 1; i++) {
  const xMid = (points[i].x + points[i + 1].x) / 2;
  const yMid = (points[i].y + points[i + 1].y) / 2;
  const cpX1 = (xMid + points[i].x) / 2;
  const cpX2 = (xMid + points[i + 1].x) / 2;
  ctx.quadraticCurveTo(cpX1, points[i].y, xMid, yMid);
  ctx.quadraticCurveTo(cpX2, points[i + 1].y, points[i + 1].x, points[i + 1].y);
}

to create a for loop that gets the midpoint x and y coordinates with

const xMid = (points[i].x + points[i + 1].x) / 2;
const yMid = (points[i].y + points[i + 1].y) / 2;

We get the x coordinate endpoints with

const cpX1 = (xMid + points[i].x) / 2;
const cpX2 = (xMid + points[i + 1].x) / 2;

And then we call quadraticCurveTo method to draw the point from the current point to midpoint.

Then we call quadraticCurveTo again to draw the curve between the midpoint between the midpoint and the next point and the next point.

Conclusion

To draw smooth curve through N points using JavaScript HTML5 canvas, we create a loop that calls the canvas context quandraticCurveTo method with the end and midpoints.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *