Question

I'm making a game that uses pixi and it renders on a canvas that's 640x480 pixels. As you can imagine, this is very small when viewed on a PC. I'd like to accomplish this:

  1. I want to increase the size of the canvas so it fills up the whole screen
  2. I want to zoom in on the content so that it fills up as much as possible without changing its aspect ratio
  3. I'd like to center the canvas if there's left over space from the previous step

When I google for how to do this in pixi, I can find each of these individually. But I'd like to have the information on how to do this all in one place and on stackoverflow, because you usually want to do all of these things together.

Was it helpful?

Solution

I modified the source code in this example made by the creator: http://www.goodboydigital.com/pixi-js-tutorial-getting-started/ (source download)

Here's what I came up with:

<!DOCTYPE HTML>
<html>
<head>
    <title>pixi.js example 1</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #000000;
        }
    </style>
    <script src="pixi.js"></script>

</head>
<body>
    <script>

    // create an new instance of a pixi stage
    var stage = new PIXI.Stage(0x66FF99);

    // create a renderer instance
    var renderer = PIXI.autoDetectRenderer(400, 300);
    renderer.resize(800, 600);

    // add the renderer view element to the DOM
    document.body.appendChild(renderer.view);

    requestAnimFrame( animate );

    // create a texture from an image path
    var texture = PIXI.Texture.fromImage("bunny.png");
    // create a new Sprite using the texture
    var bunny = new PIXI.Sprite(texture);

    // center the sprites anchor point
    bunny.anchor.x = 0.5;
    bunny.anchor.y = 0.5;

    // move the sprite t the center of the screen
    bunny.position.x = 200;
    bunny.position.y = 150;

    var container = new PIXI.DisplayObjectContainer();
    container.scale.x = 2;
    container.scale.y = 2;
    container.addChild(bunny);
    stage.addChild(container);

    function animate() {

        requestAnimFrame( animate );

        // just for fun, lets rotate mr rabbit a little
        bunny.rotation += 0.1;

        // render the stage
        renderer.render(stage);
    }

    </script>

    </body>
</html>

Now the one thing I didn't do is center it. I see two potential ways to do this. I could use CSS to center the canvas (what I'll probably use), or I could do this in code by adding another outer display object to the stage that centers container.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top