LoginSignup
0
0

More than 1 year has passed since last update.

Pixi.jsでドット絵のSpriteを綺麗に拡大する

Posted at

修正前のコード(ぼやける)

index.html
<html>

<head>
    <link rel="stylesheet" href="index.css" />

    <!-- jQueryの読み込み -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <!--pixi.js読み込み-->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.0.1/pixi.min.js"></script>
</head>

<body>
    <div id="app"></div>
    <script type="text/javascript" src="index.js"></script>
</body>

</html>
index.js
window.addEventListener('load', () => {
    let app = new PIXI.Application({
        width: 256,
        height: 192,
        backgroundColor: 0xcccccc,
    });

    app.stage.x = app.screen.width / 2;
    app.stage.y = app.screen.height / 2;
    $('#app').append(app.view);

    let sprite1 = PIXI.Sprite.from('image.png');
    sprite1.anchor.set(0.5);
    sprite1.x = -32;
    app.stage.addChild(sprite1);

    let sprite2 = PIXI.Sprite.from('image.png');
    sprite2.anchor.set(0.5);
    sprite2.x = 32;
    sprite2.scale.set(3);
    app.stage.addChild(sprite2);
});
index.css
#app canvas {
    width: 512px; /*/2倍に拡大/*/
}

image.png
image.png

全て同一ディレクトリにあります。

実行するとこんな感じ
1.PNG

画像をクリックして拡大するとわかりやすいですが3倍のスプライトも等倍のスプライトもぼやけています。
どうにかしましょう。

解決方法

  • Canvas要素を拡大した時のぼやけはCSSで調整する。
index.css
#app canvas {
    width: 512px; /*/2倍に拡大/*/
    image-rendering: pixelated;
}

2.PNG

等倍のスプライトは綺麗に表示されています。

  • プログラムで拡大設定した時のぼやけはjsで調整する
index.js
window.addEventListener('load', () => {
    PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
...

3.PNG

完璧です!

ちょっと回転させます。

index.js
...
    let sprite1 = PIXI.Sprite.from('image.png');
    sprite1.anchor.set(0.5);
    sprite1.x = -32;
    sprite1.rotation = Math.PI / 3;
    app.stage.addChild(sprite1);

    let sprite2 = PIXI.Sprite.from('image.png');
    sprite2.anchor.set(0.5);
    sprite2.x = 32;
    sprite2.rotation = Math.PI / 3;
    sprite2.scale.set(3);
    app.stage.addChild(sprite2);
});

4.PNG

回転しても大丈夫。

ちょっと高速化

PIXI.settings.ROUND_PIXELS = true;を追加します。
ピクセル補完とやらが停止して速くなるらしいです。
公式の説明(英語)

index.js
window.addEventListener('load', () => {
    PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
    PIXI.settings.ROUND_PIXELS = true;
...

5.PNG

さっきとは若干違います。

6.gif

以上!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0