可以通过 npm 或直接引入 CDN 链接来使用 PixiJS:
npm install pixi.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/7.0.0/pixi.min.js"></script>
以下是一个基本的示例,展示了如何创建一个 PixiJS 应用并绘制一个精灵:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PixiJS Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/7.0.0/pixi.min.js"></script>
</head>
<body>
<script>
// 创建一个 PixiJS 应用
const app = new PIXI.Application({ width: 800, height: 600 });
document.body.appendChild(app.view);
// 加载资源
app.loader.add('bunny', 'https://pixijs.io/examples/examples/assets/bunny.png').load((loader, resources) => {
// 创建一个精灵
const bunny = new PIXI.Sprite(resources.bunny.texture);
// 设置精灵位置
bunny.x = app.renderer.width / 2;
bunny.y = app.renderer.height / 2;
// 设置精灵锚点
bunny.anchor.set(0.5);
// 添加精灵到舞台
app.stage.addChild(bunny);
// 添加动画
app.ticker.add((delta) => {
bunny.rotation += 0.01 * delta;
});
});
</script>
</body>
</html>
PixiJS 提供了丰富的动画支持,可以轻松创建复杂的动画效果。
// 创建一个 PixiJS 应用
const app = new PIXI.Application({ width: 800, height: 600 });
document.body.appendChild(app.view);
// 加载资源
app.loader.add('bunny', 'https://pixijs.io/examples/examples/assets/bunny.png').load((loader, resources) => {
// 创建一个精灵
const bunny = new PIXI.Sprite(resources.bunny.texture);
bunny.anchor.set(0.5);
bunny.x = app.renderer.width / 2;
bunny.y = app.renderer.height / 2;
app.stage.addChild(bunny);
// 添加动画
app.ticker.add((delta) => {
bunny.rotation += 0.1 * delta;
bunny.scale.x = 1 + 0.5 * Math.sin(app.ticker.lastTime / 100);
bunny.scale.y = 1 + 0.5 * Math.cos(app.ticker.lastTime / 100);
});
});
PixiJS 提供了多种内置的滤镜和效果,可以轻松添加各种视觉效果。
// 创建一个 PixiJS 应用
const app = new PIXI.Application({ width: 800, height: 600 });
document.body.appendChild(app.view);
// 加载资源
app.loader.add('bunny', 'https://pixijs.io/examples/examples/assets/bunny.png').load((loader, resources) => {
// 创建一个精灵
const bunny = new PIXI.Sprite(resources.bunny.texture);
bunny.anchor.set(0.5);
bunny.x = app.renderer.width / 2;
bunny.y = app.renderer.height / 2;
app.stage.addChild(bunny);
// 添加模糊滤镜
const blurFilter = new PIXI.filters.BlurFilter();
blurFilter.blur = 5;
bunny.filters = [blurFilter];
});
PixiJS 允许开发者创建自定义渲染器,以实现特定需求。
// 自定义渲染器示例
class CustomRenderer extends PIXI.ObjectRenderer {
constructor(renderer) {
super(renderer);
}
start() {
// 初始化渲染器
}
flush() {
// 刷新渲染器
}
render(element) {
// 渲染元素
}
destroy() {
// 销毁渲染器
}
}
PIXI.Renderer.registerPlugin('custom', CustomRenderer);
options.width
(number): 画布的宽度。options.height
(number): 画布的高度。options.view
(HTMLCanvasElement): 用于渲染的画布元素。options.transparent
(boolean): 画布是否透明。options.backgroundColor
(number): 画布的背景颜色。PIXI.Sprite(texture): 创建一个新的精灵对象。
texture
(PIXI.Texture): 精灵使用的纹理。sprite.anchor: 设置精灵的锚点。
sprite.x: 设置精灵的 x 坐标。
sprite.y: 设置精灵的 y 坐标。
sprite.rotation: 设置精灵的旋转角度。
sprite.scale: 设置精灵的缩放比例。
blur
(number): 模糊程度。PixiJS 是一个功能强大且易于使用的 2D 渲染引擎,通过简单的 API 提供高性能的图形和动画功能。无论是游戏开发、数据可视化还是交互式应用,PixiJS 都是一个理想的选择。