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
- Create a Graphics Object: Instantiate a new
Graphicsobject which will contain your vector drawing instructions. - Define the Line Style: Set the thickness, color,
and opacity of the curve using the
lineStylemethod (orstrokein Pixi.js v8+). - Set the Starting Point: Move the drawing path’s pen
to the beginning of the curve using
moveTo(startX, startY). - 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. - 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
moveTo(startX, startY): Establishes the origin point of your curve. If you do not call this, the curve will start from the default coordinate(0, 0).controlX, controlY: The coordinates of the single control point. The curve will bend toward this coordinate but will not actually touch it.endX, endY: The final coordinates where the curve terminates.