Quantcast
Channel: Pixi.js Latest Topics
Viewing all 3978 articles
Browse latest View live

What is the correct way to use loaded JSON texture atlas?

$
0
0

Hello,

I'm just stasting out with PIXI and making games in general as a hobby.
Now I followed the tutorial here: https://github.com/kittykatattack/learningPixi#creating-sprites-from-a-loaded-texture-atlas and it says there are three general ways to create a sprite from a texture atlas:  (edited a bit)

//1. Access the `TextureCache` directly 
dungeon = new Sprite(PIXI.utils.TextureCache["dungeon.png"]);

//2. Access the texture using the loader's `resources`:
explorer = new Sprite(    resources["images/treasureHunter.json"].textures["explorer.png"]  );
  
//3. Create an optional alias called `id` for all the texture atlas 
id = PIXI.loader.resources["images/treasureHunter.json"].textures; 
treasure = new Sprite(id["treasure.png"]);


Out of those three accessing the TextureCache directly seems the easiest to me, but I noticed that there are no errors if I mistype the texture's name. So that could couse alot of irritating issues sometimes. It has already coused some headaches.

the example here: https://pixijs.github.io/examples/#/basics/spritesheet.js uses yet another way to make use of the loaded textures:
// magically works since the spritesheet was loaded with the pixi loader
 [...]  PIXI.Texture.fromFrame('rollSequence00' + val + '.png');

This, I noticed DOES throw an error to the console if I mistype the name.

So PIXI.Texture.fromFrame seems to be the best way I have seen so far. But it's kinda confusing now, all these different ways.


Anyway, what's the correct way to use textures from a spritesheet loaded with a JSON file?


 


[PIXI] Loading Video files?

$
0
0

Hello,

 

Could anyone out there suggest the best-practise for loading and accessing video files with Pixi?

 

I understand that the current version of Pixi's loader doesn't support loading videos.

So it seems that the only way to load and use them is to use the `fromVideo` and `fromVideoUrl` methods.

Because video files tend to be huge, is there any way to monitor load progress or fun a callback when they're loaded?

 

Thanks!

 

Pixi.JS / Pan & Zoom Canvas

$
0
0

Hi,

I'm using Pixi since several days on a game prototype which consists in a map made of tiles.

The problem is that I got a big map (2000px / 2000px), so it don't fit a desktop screen, and not any mobile screen.

I am looking for a way to allow the user to

  • pan (i.e. navigating on the canvas with mouse drag and drops (for desktop) and with the finger (for mobile devices)
  • zoom in / out the canvas

Like in google maps for example

Any idea of an embedded feature I can use?

 

Thanks in advance for you answers.

How to make the sprite move with the container but not scale

$
0
0

Hi guys,

How do I make it that the black square moves with the red square but NOT scale?

Example: jsfiddle

When you click on the small blue square the big white square gets smaller. The big red square scales with the white square. This is what I want but... the little black square should not scale but change position, is that possible? The black square should be in the red square BUT with the same height and width.

reusing texture with different frames

$
0
0

Trying to reuse a texture with different frames to populate various sprites. Every sprite gets the same frame however.

In my setup function called from loader:

  cells.forEach((row)=>{
    row.forEach((col)=>{
      // create sprite
      let frame = selectTerrain(col);
      console.log(frame);
      let txt = PIXI.loader.resources[terrainSource].texture;
      txt.frame = frame;
      let cell = new Sprite(txt);

      cell.x = col.x;
      cell.y = col.y;
      addText(cell, col.row, col.col);

      baseCont.addChild(cell);
    });
  });

// randomly select grass or default to water
function selectTerrain(cell){
  var ref = cell.row + ","+cell.col;
  console.log("process cell " + ref);
  
  if(cell.row > 0 && cell.col > 0 && cell.col < (maxCol-1) && cell.row < (maxRow-1)){
    let rand = Math.random();
    if(rand > 0.5){
      return new Rectangle(610, 142, 120, 140);
    }
  } 
    return new Rectangle(853, 0, 120, 140);

}

What is the correct way to get different frames from a cached tilesheet?

PIXI current versions in the future ?

$
0
0

Hello, developers! 

I am wondering about PIXI v.3 or v.4, how much they can live and work on the internet.

Imagine now I start big project on v.3 or v.4. This project should be licensed with little exceptions.

Should I extract the whole code related to PIXI(my view) to be specially maintained over the time?

What is the experience on similar cases?

What is the risk? 



 

How to crop/hide over flow of sprites which clip outside of the world boundaries

$
0
0

Considering:

hookem-clip-bug.thumb.png.19195b71fedcc43a4d3397ef98b4c1c0.png

I am curious if there is some sort of configuration which can crop drawings outside a particular boundary? 

Thanks

 

 

Get parent width\height on added

$
0
0

Hello.

I'v got a trouble and don't understand how to fix it.

I need to store a percent of width\height of a child object according to its parent. Those children can change its parents. So every child do that on a constructor:

constructor(){
   this.on('added', onAdded, this)
}

onAdded(){
   this.percentWidth = this.width / this.parent.width;
   this.percentHeight = this.height / this.parent.height;
}

When i'v got small number of children everything is ok. But if i am trying to add 30000+ children to a container\stage, this.parent.width begin to recalculate its bounds in exponential time, and causes page to hang.

Overriding _calculateBounds won't help because parent.width will go again through 30000 children and calculate 30000*30000 times its bound.

when calling addChild, a parent container do

//core/display/Container.js
addChild(child)
{
    ...

    this._boundsID++;

and causes to execute calculateBounds again even if skipUpdate = true

//core/display/DisplayObject.js

getBounds(skipUpdate, rect)
    {
        if (!skipUpdate)
        {
            if (!this.parent)
            {
                this.parent = this._tempDisplayObjectParent;
                this.updateTransform();
                this.parent = null;
            }
            else
            {
                this._recursivePostUpdateTransform();
                this.updateTransform();
            }
        }
        if (this._boundsID !== this._lastBoundsID)
        {
            this.calculateBounds(); 
        }

You can see that online at https://pixijs.io/examples/#/basics/container.js and paste this

var app = new PIXI.Application(800, 600, {backgroundColor : 0x1099bb});
document.body.appendChild(app.view);

var container = new PIXI.Container();

app.stage.addChild(container);

var texture = PIXI.Texture.fromImage('required/assets/basics/bunny.png');

function bug(){
  let w = 0; //this.parent.width;
  let h = 0; //this.parent.height;
}


for (var i = 0; i < 30000; i++) {
    var bunny = new PIXI.Sprite(texture);
    bunny.on('added',bug,bunny);
    bunny.anchor.set(0.5);
    bunny.x = Math.random()*800;
    bunny.y = Math.random()*600;
    container.addChild(bunny);
}

// Center on the screen
container.x = (app.screen.width - container.width) / 2;
container.y = (app.screen.height - container.height) / 2;

 

So is there any way to operate parent.width\height when child is added to a parent?

Probably the best way is to calculate this.percentWidth\Height on a getter, but may be there is some other way out

Thanks. Sorry for bad english and long post 


Repeated Texture

$
0
0

Hi,

I want to achieve a repeated texture effect something like this:

Clipboard02.png.b51106ea27b4da537b35aa1a6171c220.png

In plain OpenGL you can set the texture wrap to GL_REPEAT and multiply the UV's by a factor and your are done.

 

In Pixi i've tried PIXI.extras.TilingSprite (with hundreds of objects) but this seems to be very slow on my MacBook.

 

So i thought it would be possible by simply changing the UVs and set the texture wrap mode to repeat but this does not work:

let resources = PIXI.loader.resources;

let tex = resources[item.texture].texture;
tex.wrapMode = PIXI.WRAP_MODES.REPEAT;

//texture size is 128x128 
let texRectangle = new Rectangle(0, 0, 256, 256);
tex.frame = texRectangle;

let pixiItem = new Sprite(tex);

//using this instead I have a FPS drop from 60fps to 5fps
let pixiItem = new PIXI.extras.TilingSprite(tex);

With a little research I found this:

https://github.com/pixijs/pixi.js/commit/7db340ce8e62de3a14bc796fe34fe344de27a701#diff-450b030630803a4d2e7ad3ba09ff17f6

It seems that texture coordinates are now based on UINT16. So a float based scale would not be possible

 

Any hints on this? 

Thanks!

Set Cotainer bounding boxes

$
0
0

So I have a "radar" on one side of my stage which shows the current position of the player on the map.

It does not display all of the map, just a small sector, additionally the map radar follows the rotation of the player and shows some enemies.

 

Basically I've got a huge map texture (2048x2048) and the radar should only display a 256x256 segment, inside my gameLoop the mapTexture would be moved so that current player position is in the containers center, then all enemies get drawn onto it, and finally I rotate the whole radar container to match players rotation.

 

But PIXI.Container is just a base object. I've found this example: https://github.com/pixijs/pixi.js/issues/2051

Unfortunately it is very old (still uses renderer.render()) and I couldn't get it to work. So my question is now: how would one achive this the most efficient way without handling all "off-screen" player/objects? Overriding PIXI.Container.prototype.addChildAt and removing the call to calculateBounds()? Using an updated version of the issues' example? 

Need faster result than pixel() to get filter output

$
0
0

I have a very simple graphics with a custom filter that creates a Noise + basic sin calculation to create a wave displacement map. I need to get the result of only one channel and I'm currently using :

renderer.extract.pixels()

But it is VERY slow. Is there a way to get the data output directly from the shader instead? I'm not sure if I'm explaining well enough...

In other words, I would like to have the gl_FragColor of each pixels directly after the filter calculation. I'm pretty sure it should be possible instead of waiting for the Renderer to calculate the exact same result based on the position of the graphics, and then extracting it.

I have search for several hours everywhere...

Here's what I have at the moment (in Typescript), but the pixel() consume 49% of the tick duration.

private createTextureDeformer() : void {
        this._pixiApp = new PIXI.Application(this.textureResolution + 1, this.textureResolution + 1, {
            transparent : <any> "notMultiplied",
        });

        var uniforms : any = {};
        uniforms.u_time = {
            type : 'f',
            value : 0
        };

        uniforms.u_size = {
            type : 'i',
            value : this.textureResolution
        };


        this._textureFilter = new PIXI.Filter(null, this.getTextureDeformerShader(), uniforms);

        var graphics : PIXI.Graphics = new PIXI.Graphics();
        graphics.drawRect(0, 0, this.textureResolution, this.textureResolution);

        graphics.filters = [this._textureFilter];
        this._pixiApp.stage.addChild(graphics);

        if(this.debug) {
            document.body.appendChild(this._pixiApp.view);
            this._pixiApp.view.id = 'pixi-canvas';
        }

        this.renderTextureDeformer(0);
    }

private renderTextureDeformer(delta : number) : void {
        this._textureFilter.uniforms.u_time += delta / 1000;
        this._texturePixels = this._pixiApp.renderer.extract.pixels() as Uint8Array;
    }

 

Load all assets in a folder

$
0
0

I was looking through the Loader class, and it seems that in order to load an asset, I need to name each file, like in:
loader.add('example-sprites', 'example-sprite-sheet.json');

Is it possible to load all of the files in a folder without specifying each one by name? I know that I'd like to cache all the files within a specific folder, but I don't actually know what the filenames are prior to loading. 

If this isn't possible, what would be the best practice for this sort of situation when the files aren't known?

Really appreciate any advice on this-- thanks in advance! :)

 

CanvasTinter newb question

$
0
0

Hello,

I was working with a simple canvas app (for now we can't use the webgl renderer so we're stuck with canvas) and we're trying to colorize some sprites. Since we're using canvas filters and shaders are out of the question so I was wondering if this is somehow possible using canvas?.

I created a simple test using canvas tinter but the result is a fully painted canvas and not a tinted texture:

const app = new PIXI.Application(800, 600, {
	backgroundColor: 0x9cbac9, autoResize: true, forceCanvas: true
});

document.getElementById("app").appendChild(app.view);

const bgTexture = PIXI.Texture.fromImage("https://s3-us-west-2.amazonaws.com/s.cdpn.io/33073/landscape.jpg");

PIXI.CanvasTinter.tintWithMultiply(bgTexture, "rgba(179, 179, 179, 0.5)", app.renderer.context.canvas);

const bg = new PIXI.Sprite(bgTexture);

app.stage.addChild(bg);

Here's a live sample:

https://codepen.io/rhernando/pen/620bdae58717e0d3af021db73f096155?editors=0010

Thanks,
Rodrigo.

All the graphics sometimes disappear when loading finishes

$
0
0

Hello everyone. In my 100k+ lines_of_code project in late weeks was introduced a bug which sometimes causes all the graphics to disappear at the end of loading process.

Could you please help me to hunt it down?

First, game loads background and loading bar with PIXI.loader and displays it with PIXI. Then loads all the other resources the same way. When other resources finish loading there is a chance (50% for some machines and <1% for others) that none will be displayed and both background and loading bar also disappear.

When it happens, line:

PIXI.renderer.render( stage )

throws these errors (currently using PIXI 4.5.3):pixi.thumb.png.73229538266bc7f75d1063d0f895bdee.png

where Sprite.js:208 of my version is sprite_208.png.31ca960f13cfa9fea78613c3e7c88ec7.png

and WebGLRenderer.js:408 is webglrenderer_480.png.bfb795801b4833e0a61b830edcc0b405.png

I was trying to examine and reverse every change made to the project for last weeks, but they are pretty innocent and it didn't help :(

What I figured out so far is that sprite.baseTexture.orig of every existing image somehow becomes null at some point and every width() getter stops working which throws such exceptions, but weird part is that these errors are only thrown once - not every requestAnimationFrame() call, hmm. And I couldn't find any line in PIXI and PIXI.loader where there would be something like sprite.baseTexture.orig = null or BaseTexture: this.orig = null ...

Do you guys have any ideas what could cause such behavior and any possible steps to fix it? Thanks in advance! ;)

How to fill area between two lines?

$
0
0

I have to make a chart that fills the area between two lines looks like in below. 

image.thumb.png.04327536bdd32a53b63c7c4cbc3db644.png

I have calculated and drawn two lines and connected each lines (See below image)

image.thumb.png.f030dc14352e49334b7ae03487970589.png

And I have used 2 approaches to complete this task.

  1. drawPolygon
  2. Using color for beginFill

and both time I have failed. (See in below)

image.thumb.png.9dbd8b74e8033ebae79b9d323c22a18e.png

Please advice me. 


PIXI.Text with solid color background

$
0
0

hey guys,

I'm wondering if there is an easy and efficient way to add background to the PIXI.Text object. For now, my plan is to add a scaled solid color image as background and put them in the right position. Not sure if this is the recommended way.

 

Thanks

Saving PIXI content to Image

$
0
0

Guys,

We recently have new requirement that we need to save the content we rendered with pixi.js to image file like PNG.

The canvas's toDataURL method worked well at first, however  we need more than that.

 

The content (a diagram) could be zoomed and the canvas only shows part of that diagram at the time we save the image.

Also, if we zoom out and try to capture the whole diagram, the output diagram seems not so crisp, or sharp. Hope I've made my self clear.

So, my question is whether their is a way to export the whole content image with desired resolution?

 

BR,

Yeling

 

Pixi.js Showcase

$
0
0

Made anything cool with pixi.js? Post it up here and share it with the world!

 

Whether it's a cool game demo, a fully fledged website or some tripped-out crazy experiment, we would all LOVE to see it!

 

To get the ball rolling, here are some pixi.js projects that exist out on the internets:

 

games:

 

http://www.goodboydigital.com/runpixierun/

http://www.theleisuresociety.co.uk/fightforeveryone/

http://flashvhtml.com/

 

experiments:

 

http://gametest.mobi/pixi/morph/

http://gametest.mobi/pixi/balls/

http://www.goodboydigital.com/pixijs/bunnymark/

 

 

 

 

 

Loading Video As Data URI?

$
0
0

Is it possible to load video as data URI?

I tried to pass the data uri for a video and nothing appears.

It works fine if I load regular video file.

 

This is my code, videoData is a string for the data uri of the mp4 video I am testing. Passing videoData  = ' myVideo.mp4' works fine but when I pass videoData = '_insert_data_uri_string_here_' it doesn't work

var texture = PIXI.Texture.fromVideo(videoData);
var videoSprite = new PIXI.Sprite(texture);
videoSprite.anchor.set(0.5);
videoSprite.x = app.screen.width / 2;
videoSprite.y = app.screen.height / 2;

app.stage.addChild(videoSprite);

Does pixi support data uri for videos?

Thanks.

I am using PixiJS 4.8.2 - ✰ WebGL ✰     http://www.pixijs.com/    ♥♥♥ 

Best way to extract a very large container/sprite

$
0
0

Hi Guys,

I am working on a large scale interactive data visualization dashboard using the latest version of Pixi. For this project I am aiming to support IE11, and the latest versions of the popular browsers.

As of now I am stuck on extracting/exporting the bar chart, which can easily contain a thousand rows (and uses a self made scrollbar).

A bar chart basically is a container and a row in the chart is a sprite with a height of 30px.

I tried the following approach: 

 

However, I am limited by the maximum size of the canvas. (see here: https://stackoverflow.com/questions/6081483/maximum-size-of-a-canvas-element).

For now I am considering building new containers (< max height of the canvas) and filling them with row sprites. However, I would prefer to export the chart as a single file.

Does anyone have ideas as to how they would approach this? 

Thanks a lot!

Wilco

 

Viewing all 3978 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>