Categories
JavaScript Answers

How to Draw a Smooth Curve Through N Points Using JavaScript HTML5 Canvas?

Spread the love

We can use the quadraticCurveTo method that comes with the canvas context object to draw a curve through n points.

To use it, we can first write the following HTML:

<canvas width="200" height="200"></canvas>

Then we can use it by writing:

const points = [{
  x: 1,
  y: 1
}, {
  x: 20,
  y: 30
}, {
  x: 30,
  y: 40
}, {
  x: 40,
  y: 20
}, {
  x: 50,
  y: 60
}]

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d")
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);

for (const point of points) {
  const xMid = (point.x + point.x) / 2;
  const yMid = (point.y + point.y) / 2;
  const cpX1 = (xMid + point.x) / 2;
  const cpX2 = (xMid + point.x) / 2;
  ctx.quadraticCurveTo(cpX1, point.y, xMid, yMid);
  ctx.quadraticCurveTo(cpX2, point.y, point.x, point.y);
}
ctx.stroke();

We have the points array that has the x and y coordinates of some points.

Then we get the canvas with document.querySelector .

Next, we call the getContext method to get the context object.

Then we call beginPath to start drawing.

And then we call moveTo to move to the first point.

Next, we call quadraticCurveTo to draw the curve from the first point that we calculated from the (cpX1 , point.y) to (xMid ,yMid).

Then we draw the curve from (cpX2 , point.y ) to (point.x , point.y ).

cpX1 and cpX2 are the center points of x and y for the line segment between one point and the next.

And finally, we call stroke to draw the line onto the screen.

By John Au-Yeung

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

One reply on “How to Draw a Smooth Curve Through N Points Using JavaScript HTML5 Canvas?”

Leave a Reply

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