javascripthtml5-canvaspixi.js

PIXI.js create avatar from image


I would like to style an image with a rectangular/square shape which is loaded as a PIXI.JS Sprite to look like an avatar with a circular shape.

Here is my code sample:

import "./styles.css";
import * as PIXI from "pixi.js";

let app = new PIXI.Application({
  width: 800,
  height: 600,
  antialiasing: true,
  transparent: false,
  resolution: 1,
});

document.body.appendChild(app.view);

//To change the background color
app.renderer.backgroundColor = "0x000000";

PIXI.loader.load(() => {
  const avatar = PIXI.Sprite.from(
    "https://scontent.fsof10-1.fna.fbcdn.net/v/t39.30808-6/328967084_733962544767181_6767350406211342384_n.jpg?_nc_cat=110&ccb=1-7&_nc_sid=5f2048&_nc_ohc=I8xWlna0c1YQ7kNvgGPzMDD&_nc_ht=scontent.fsof10-1.fna&oh=00_AfBH5ijJzlok_XqCN4BPrcjzN2Nj4qMNAHCXr4jqDfh04Q&oe=663E9A2D"
  );

  avatar.width = 100;
  avatar.height = 100;
  avatar.x = 100;
  avatar.y = 200;
  app.stage.addChild(avatar);
});

Link to a playground: https://codesandbox.io/p/sandbox/pixi-playground-forked-td9x22


Solution

  • I assume by 'styling something like an avatar with a circular shape' you're referring to something like this:

    This is called masking - meaning a source(image) is only visible where it intersects with a target(image) - in your case the circular shape.

    This can be done rather easily using Pixi.js Graphics API to draw a plain circle and assigning this mask to a Sprite's .mask property.

    (async () => {
        let app = new PIXI.Application();
        await app.init({
            width: 400,
            height: 300
        });
        document.body.appendChild(app.canvas);
    
        const texture = await PIXI.Assets.load('https://scontent.fsof10-1.fna.fbcdn.net/v/t39.30808-6/328967084_733962544767181_6767350406211342384_n.jpg?_nc_cat=110&ccb=1-7&_nc_sid=5f2048&_nc_ohc=I8xWlna0c1YQ7kNvgGPzMDD&_nc_ht=scontent.fsof10-1.fna&oh=00_AfBH5ijJzlok_XqCN4BPrcjzN2Nj4qMNAHCXr4jqDfh04Q&oe=663E9A2D');
        const avatar = new PIXI.Sprite(texture);
        avatar.width = 100;
        avatar.height = 100;
        avatar.x = 100;
        avatar.y = 200;
    
        avatar.anchor.set(0.5);
    
        avatar.x = app.screen.width / 2;
        avatar.y = app.screen.height / 2;
    
        const mask = new PIXI.Graphics();
    
        mask.circle(avatar.x, avatar.y, 50);
        mask.fill({
            color: 0x000000
        });
    
        avatar.mask = mask;
        app.stage.addChild(avatar);
    })();
    <script src="https://pixijs.download/v8.1.0/pixi.js"></script>