Home  >  Article  >  Web Front-end  >  How to Draw Smooth Curves in Canvas with Multiple Points?

How to Draw Smooth Curves in Canvas with Multiple Points?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 00:30:30374browse

How to Draw Smooth Curves in Canvas with Multiple Points?

How to Draw Smooth Curves with Multiple Points in JavaScript and HTML5 Canvas

Issue:

Creating smooth curves in drawing applications by joining sample points with "curveTo" functions results in kinks due to disjointed control points.

Solution:

To draw a smooth curve through N points, an alternative approach is to "curve to" the midpoints between subsequent points.

Code:

<code class="javascript">// Move to the first point
ctx.moveTo(points[0].x, points[0].y);

// Iterate through points
for (var i = 1; i < points.length - 2; i++) {
  // Calculate midpoint
  var xc = (points[i].x + points[i + 1].x) / 2;
  var yc = (points[i].y + points[i + 1].y) / 2;

  // Create quadratic curves to midpoints
  ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc);
}

// Curve through the last two points
ctx.quadraticCurveTo(
  points[i].x,
  points[i].y,
  points[i + 1].x,
  points[i + 1].y
);</code>

Explanation:

This method approximates a smooth curve by joining curves at the midpoints of adjacent points. Each disjointed curve shares an endpoint but is influenced by common control points, resulting in smooth transitions at intersecting points.

Note:

While this approach does not draw through every sample point as originally stated in the question title, it produces visually indistinguishable smooth curves that suffice for most drawing applications.

The above is the detailed content of How to Draw Smooth Curves in Canvas with Multiple Points?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn