用PixiJS实现react图标旋转动效

1,479 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情

什么是PixiJS

PixiJS是一个开源的基于web的渲染系统,为游戏、数据可视化和其他图形密集型项目提供了极快的性能。具体细节可移步PixiJS官网

18680c9ffc1a6dc4849367e6297e2d7.png

PixiJS初探

首先我们在html中引入pixijs,打印PIXI看看都暴露了哪些API

<!doctype html>
<html>
<head>
  <script src="https://pixijs.download/release/pixi.min.js"></script>
</head>
<body>
  <script>
    console.log(PIXI)
  </script>
</body>
</html>

354e7c02b54be4a6229a3ae89509c2e.png

我这只截了一部分,PIXI这个全局变量暴露了大量的属性和方法,我们今天只抛砖引玉学习其中最最简单的部分

PIXI.Application

我们可以使用PIXI.Application来创建一个app实例:

let app = new PIXI.Application({ width: 640, height: 360 });

然后把app视图添加到body上:

document.body.appendChild(app.view);

4bc6dbe8ceeb4ff91629d45b0ccf831.png 一片漆黑,没错,就是这样,我们可以在创建app的时候配置更多的属性,比如颜色(颜色必须是16进制数):

let app = new PIXI.Application({ width: 640, height: 360, backgroundColor: 0xf8b62a });

8d836bc685ed783d3327dd66dc8adcf.png

ok,我们初步掌控了页面,下面我们继续深入探讨其他功能。

PIXI.Sprite

我们可以使用PIXI.Sprite来创建一个精灵图,并加到场景里:

let sprite = PIXI.Sprite.from('images/react.svg');
app.stage.addChild(sprite);

b8f72c3f69e5c3218a585a830d43e4a.png

为了看着顺眼,我们还是用默认黑色底图。是的,我们把react的图标加到我们的场景里了。一切进展顺利,是否能让它居中显示?搞起来!

sprite.x | sprite.y | sprite.anchor

sprite.x = app.screen.width / 2; 
sprite.y = app.screen.height / 2;
sprite.anchor.set(0.5);

e6e6333eae2fb47b36fe61eb7cb8d6a.png 这3行代码的意思就是将精灵图置于屏幕中间,精灵图以自生中心点为参照点(默认是左上角)。

旋转起来

app.ticker.add((delta) => {
  sprite.rotation -= 0.01 * delta;
});

11.gif

截图的gif略显卡顿,实际上这个动画是非常丝滑的,不信大家复制以下完整代码在本地试试呀:

<!doctype html>
<html>

<head>
  <script src="https://pixijs.download/release/pixi.min.js"></script>
</head>

<body>
  <script>
    console.log(PIXI)
    // Create the application helper and add its render target to the page
    let app = new PIXI.Application({ width: 640, height: 360 });
    document.body.appendChild(app.view);
    // Create the sprite and add it to the stage
    let sprite = PIXI.Sprite.from('images/react.svg');
    app.stage.addChild(sprite);
    sprite.x = app.screen.width / 2;
    sprite.y = app.screen.height / 2;
    sprite.anchor.set(0.5);
    // // Add a ticker callback to move the sprite back and forth
    app.ticker.add((delta) => {
      sprite.rotation -= 0.01 * delta;
    });
  </script>
</body>

</html>

大家觉得不错的记得点赞噢,晚安献给还在努力的你~