Use mouse to draw a line in Pixi.js

How to draw a line in pixi.js with a mouse

To draw a line with the mouse in Pixi.js, you need to listen for mouse events and update the graphics object accordingly. Here's an example of how you can achieve this:

// Create a Pixi.js application
const app = new PIXI.Application();

// Add the canvas to the HTML document
document.body.appendChild(app.view);

// Create a new Graphics object
const graphics = new PIXI.Graphics();
app.stage.addChild(graphics);

// Variables to store the starting and ending positions of the line
let startPoint = null;
let endPoint = null;

// Set up mouse event listeners
app.view.addEventListener('mousedown', onMouseDown);
app.view.addEventListener('mousemove', onMouseMove);
app.view.addEventListener('mouseup', onMouseUp);

// Function to handle the mouse down event
function onMouseDown(event) {
  startPoint = event.data.global;
}

// Function to handle the mouse move event
function onMouseMove(event) {
  if (startPoint) {
    endPoint = event.data.global;

    // Clear the previous line
    graphics.clear();

    // Set the line style properties
    graphics.lineStyle(2, 0xFF0000, 1); // (lineWidth, color, alpha)

    // Move the graphics object to the starting position of the line
    graphics.moveTo(startPoint.x, startPoint.y); // (x, y)

    // Draw the line to the current mouse position
    graphics.lineTo(endPoint.x, endPoint.y); // (x, y)
  }
}

// Function to handle the mouse up event
function onMouseUp(event) {
  if (startPoint && endPoint) {
    // Reset the starting and ending positions
    startPoint = null;
    endPoint = null;
  }
}

In this example, we create a Pixi.js application, add a PIXI.Graphics object to the stage, and set up mouse event listeners for the canvas. When the mouse is pressed down (mousedown event), we store the starting position of the line. As the mouse moves (mousemove event), we update the ending position and redraw the line. When the mouse is released (mouseup event), we reset the starting and ending positions.

Remember to include the Pixi.js library in your HTML file and set up the necessary dependencies for Pixi.js to work properly.