How to Draw Quadratic Bezier Curves in Pixi.js

This article provides a quick, step-by-step guide on how to draw a quadratic Bezier curve using the Pixi.js Graphics API. You will learn the specific methods required to define the start, control, and end points of a curve, along with a practical code example to implement in your own projects.

To draw a quadratic Bezier curve in Pixi.js, you use the quadraticCurveTo method provided by the Graphics class. Unlike a cubic Bezier curve which uses two control points, a quadratic curve uses only one control point to determine the bend of the curve.

Step-by-Step Implementation

  1. Create a Graphics Object: Instantiate a new Graphics object which will contain your vector drawing instructions.
  2. Define the Line Style: Set the thickness, color, and opacity of the curve using the lineStyle method (or stroke in Pixi.js v8+).
  3. Set the Starting Point: Move the drawing path’s pen to the beginning of the curve using moveTo(startX, startY).
  4. Draw the Curve: Call quadraticCurveTo(controlX, controlY, endX, endY) to render the curve from the starting point to the end point, bent toward the control point.
  5. Add to Stage: Add the graphics object to your PixiJS application stage to render it.

Code Example

Here is a complete code snippet demonstrating how to draw a red quadratic Bezier curve:

import { Application, Graphics } from 'pixi.js';

// Initialize the PixiJS Application
const app = new Application();
await app.init({ width: 800, height: 600, backgroundColor: 0x1099bb });
document.body.appendChild(app.canvas);

// Create the Graphics helper
const graphics = new Graphics();

// Define the line style: 4px width, red color
graphics.lineStyle(4, 0xff0000, 1);

// Define the points
const startX = 100;
const startY = 300;
const controlX = 300;
const controlY = 100; // Pulls the curve upwards
const endX = 500;
const endY = 300;

// Draw the quadratic bezier curve
graphics.moveTo(startX, startY);
graphics.quadraticCurveTo(controlX, controlY, endX, endY);

// Add the curve to the screen
app.stage.addChild(graphics);

Understanding the Parameters