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

revolt fx and pixi loader

$
0
0

Hello

Im trying to find a way to use revolt.fx outside the pixi.loader and some of the loadBundleFile loader.

The default way:

   const rfxBundleSettings = 'assets/default-bundle.json';
    const rfxSpritesheet = 'assets/revoltfx-spritesheet.json';
    const additionalAssets = ['assets/rfx-examples.json'];

    //Load bundle files and the additional example spritesheet
    fx.loadBundleFiles(rfxBundleSettings, rfxSpritesheet, null, additionalAssets).then(function (data) {

        app.ticker.add(function () {
            //Update the RevoltFX instance
            fx.update();
        });

    }).catch(function (err) {
        console.log('Error', err);
    });

What I need is a way to load the image, which is referred to  in the "revoltfx-spritesheet.json" file. I need to load that image seperately.

Something like this:

const fx = new revolt.FX(); //loaded via the script tag

    const rfxBundleSettings = 'assets/default-bundle.json';
    const rfxSpritesheet = 'assets/revoltfx-spritesheet.json';
    const additionalAssets = ['assets/rfx-examples.json'];

const image-from-revoltfx-spritesheet = 'assets/revoltfx-spritesheet.png';

    //Load bundle files and the additional example spritesheet
    fx.loadBundleFiles(rfxBundleSettings, rfxSpritesheet, null, additionalAssets).then(function (data) {

        app.ticker.add(function () {
            //Update the RevoltFX instance
            fx.update();
        });

    }).catch(function (err) {
        console.log('Error', err);
    });

and then use it in the fx.loadBundleFiles() as a parameter, or maybe  another way. I´m using Pixi, but are using a costume assetManager loader.


Gradient Color Error

$
0
0

please i need help!!

//Here is the gradient function
function Gradient(x, y, w, h, startColor, endColor){
    let p1 = x+100
    let p2 = y+50
    let p3 = x+w-100
    let p4 = y+h-80
    let cvs = document.createElement('canvas')
    cvs.width = window.innerWidth-20
    cvs.width = window.innerHeight-20
    let ctx = cvs.getContext('2d')
    let grd = ctx.createLinearGradient(p1, p2, p3, p4)
    grd.addColorStop(0, startColor)
    grd.addColorStop(1, endColor)
    ctx.fillStyle = grd
    ctx.fillRect(x, y, w, h)
    return new PIXI.Texture.from(cvs)
}
//This is the params
let x = 240
let y = 100
let h = 200
let w = 200

let a = new PIXI.Graphics()
.beginTextureFill(app.Gradient(x, y, w, h, '#ff0000', '#00ff00'))
.drawRect(x, y, w, h)
.endFill()

app.stage.addChild(a)

My output is this:
a red rectangle???, why?...

image.png.4a06aaa66c9736afe33b06fda443f1a7.png

If i use this code in javascript without pixi.js

image.thumb.png.813fe78bf0838312e9feea0a166ae7c5.png

Drop Shadow with no Blur

$
0
0

I want an unblurred drop shadow.

Essentially, every pixel's color should be replaced with the drop shadow color and the alpha value should be multiplied by the shadow's alpha value.

 

Is this possible with the DropShadowFilter? I tried setting blur: 0 on that one but it still seems to blur my shadows a bit.

Use Textures loaded by Loader in CSS?

$
0
0

Hi all, i'm developing a hybrid application that uses both the DOM and Pixi.js. Is there any way to use the textures loaded by the Loader class in CSS backgrounds, perhaps by converting them into data URIs? 

Displace image borders

$
0
0

Hey guys,

I'm using Pixi.js to create a blog page template that uses a displacement texture to distort the post images (on load, on hover and reverse it on click).

My issue is that i can't figure out how to affect the borders of my image, so when you hover it for example, the borders also move (now they are static). The image texture is displaced, but i'd like it to affect the containers borders.

I know this might sound easy, but for some reason i can't figure out what i'm missing here...

I've created a jsfiddle for live code.

here is my html

<div class="section">
  <div class="section__image" data-index="1" data-src="https://source.unsplash.com/random/">
  </div>
  <div class="section__content">
    <h2>Lorem ipsum dolor.</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis, rem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium assumenda atque distinctio eos illo minima, mollitia officiis pariatur provident! Architecto cum facilis nostrum sit voluptate. Dignissimos dolores enim quidem totam?</p>
  </div>
</div>

<div class="section">
  <div class="section__image" data-index="2" data-src="https://source.unsplash.com/random">
  </div>
  <div class="section__content">
    <h2>Lorem ipsum dolor.</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis, rem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto asperiores dicta eius, est eum itaque magnam officia perspiciatis porro sequi. Autem ea ipsa sed ullam.</p>
  </div>
</div>

<div class="section">

  <div class="section__image"  data-index="3" data-src="https://source.unsplash.com/random">
  </div>
  <div class="section__content">
    <h2>Lorem ipsum dolor.</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis, rem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad autem est incidunt iusto obcaecati provident quod sequi ut veritatis. At atque aut blanditiis consequatur distinctio dolor, et, ipsa iste nam numquam officia pariatur perferendis possimus provident quibusdam quod repellendus vitae!</p>
  </div>
</div>

<div class="section">
  <div class="section__image" data-index="4" data-src="https://source.unsplash.com/random">
  </div>
  <div class="section__content">
    <h2>Lorem ipsum dolor.</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis, rem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consectetur eius nemo perspiciatis quia sit temporibus.</p>
  </div>
</div>

Here is my css

* {
  box-sizing: border-box; 
}

html, body {
  height: 100%; 
}

body {
  margin: 0; 
  font-family: 'Helvetica', serif;
}

.section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  padding: 50px 0;
  max-width: 960px; 
}

.section__image {
    position: relative;
    overflow: hidden;
    flex-shrink: 0;
    width: 100%;
    height: 100%;
}

.section__image > img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
}

.section__content {
    padding: 10px 0 0; 
}

And here is my javascript

// Note : Resize logic to fit the textures with canvas => https://github.com/pixijs/pixi.js/wiki/v4-Tips,-Tricks,-and-Pitfalls#resizing-renderer

class ImageLoader {
  constructor(element) {
    this.wrapper = element;
    this.width = element.getBoundingClientRect().width;
    this.height = element.getBoundingClientRect().height;
    this.src = element.dataset.src;
    this.mouseOn = false;
    this.animated = false;

    this.app = new PIXI.Application(this.width, this.height, {transparent: true});
    this.wrapper.append(this.app.view);
    this.container = new PIXI.Container();
    const parent = this.app.view.parentNode;
    this.app.renderer.resize(parent.clientWidth, parent.clientHeight);
    this.app.stage.addChild(this.container);

    this.load(this.startAnimation.bind(this));
  }

  load(afterLoad) {
    let tmpImg = new Image();
    tmpImg.src = this.src;
    tmpImg.addEventListener('load', () => {
      afterLoad();
    });
  }

  startAnimation() {
    const that = this;
    // create pixi image and add it to container
    this.bg = PIXI.Sprite.fromImage(this.src);
    //this.bg.width = this.app.screen.width;
    this.bg.width = this.width;
    // this.bg.height = this.height;
    this.bg.position.x = 0;
    this.bg.position.y = 0;
    this.container.addChild(this.bg);
    // create filter
    this.displacementSprite = PIXI.Sprite.fromImage('https://s3-us-west-2.amazonaws.com/s.cdpn.io/123024/disp5.jpg');
    this.displacementSprite.texture.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT; // cover with filter all image
    this.displacementFilter = new PIXI.filters.DisplacementFilter(this.displacementSprite);
    // set filter scale
    this.displacementFilter.scale.set(1e4 + Math.random()*1000);
    this.displacementSprite.scale.set(0.4 + 0.6*Math.random());
    // add filter to container & stage (for waves effect on hover)
    this.app.stage.addChild(this.displacementSprite);
    this.container.filters = [this.displacementFilter];

    this.click();

    // animate displacementFilter on image
    let tl = new TimelineMax({onComplete:function() {that.animated = true;}});
    tl.to(that.displacementFilter.scale,1,{x:1,y:1});

    this.hover();
  }

  click() {
    let that = this;
    this.wrapper.addEventListener('click',() => {
        let tl = new TimelineMax(
          {onComplete:function() {that.animated = true;}}
          );
        tl.to(that.displacementFilter.scale,1,{x:1,y:1});
    });
  }

  hover() {
      let that = this;

    this.wrapper.addEventListener('mouseenter',function() {
      if(!that.mouseOn && that.animated) {
        that.mouseOn = true;
        TweenMax.ticker.addEventListener('tick',that.doWaves, that); // same as requestAnimationFrame
        let tl = new TimelineMax();
        tl.to(that.displacementFilter.scale,0.5,{x:20,y:10});
      }

    });

    this.wrapper.addEventListener('mouseleave',function() {
      if(that.mouseOn && that.animated) {
        that.mouseOn = false;
        TweenMax.ticker.removeEventListener('tick',that.doWaves, that);
        let tl = new TimelineMax();
        tl.to(that.displacementFilter.scale,0.5,{x:1,y:1});
      }
    });
  }

  doWaves() {
    this.displacementSprite.x += 1;
  }
}

const imageNodeList = document.querySelectorAll( '.section__image');
Array.prototype.forEach.call(imageNodeList, function (node) {
  const img = new ImageLoader(node);
});

 

update my video

$
0
0

hi,

I'm completely new to pixi.js and i have trouble to replace a video by another video  in my canvas.

i wrote this code to launch the first video :

        const video = PIXI.Texture.from('img/dc.mp4');
        far = new PIXI.extras.TilingSprite(video19201080);
   stage.addChild(far);

....

 

 

and when i want to replace this video i used this :

   video.destroy(true);
   far.destroy(true);
   var video2 = PIXI.Texture.fromVideo('img/sd9.mp4');
   far = new PIXI.extras.TilingSprite(video219201080);
 
stage.addChild(far);

it works but i ve some errors in the console :

it say :

TypeError: this.source is null 

TypeError: null has no properties

and the number of this last error is growing in time ;

 

Can someone explain me what is wrong and what should i do to resolve those errors. i don't know if there is a more simple way to update the video.

Thanks,

Pierre

 

 

 

 

Fabric.js select and transform suggestions in Pixi.js

$
0
0

Any recommendation for equivalent functionality of Fabric.js selection and transformation with Pixi.js?

fabric.gif.dc44582d5eba4352f5f4c196bd5dc44a.gif

Anything like this been endeavored for Pixi.js?  Maybe a similar library out there?

Another collision detection discussion

$
0
0

Hi all,

I'm new to Pixi.js, so excuse me, if the answer to my question is obvious.

I'm building a 2d platformer where I have a PIXI.Container which contains a few sprites (let say player's arm, body, head etc.).

Based on the user input I'm moving the whole container (not each sprite individually). I also have container which contains all platforms of the level (they are all of type PIXI.Spirte).

I want to detect when the player's container intersects with any of the platforms and stop the container from moving forward (the usual stuff).

Currently I'm using the Bump.js library (https://github.com/kittykatattack/bump). But I'm encountering few problems.

First of all Bump.js doesn't work for 'container vs array with sprites' type of collision, so I've tried to detect an intersection between each player's sprite against the array with platforms. Basically I'm using the following:

player.move(); // move the player's container to any direction
BUMP.hit(playersArm, platformsArray, true, false, true);
BUMP.hit(playersBody, platformsArray, true, false, true);
BUMP.hit(playersHead, platformsArray, true, false, true);

This is testing for intersection between each player's sprite and stops it from moving, if there is a collision. All this is working fine and if there is an intersection the intersecting player's sprite position will be set to a value that is not intersecting with the platforms. However all the other sprites will continue moving, as they are not yet intersecting with the platforms. Hope I expressed myself clear.

Have you ever had such problem and how did you solve it? I can only think of building a custom collision detection logic which works with 'container vs array with sprites', so I don't have to care for each player's sprite individually, but work with the container. Do you know of any library that already handled such cases?

Or maybe I've been wrong from the start by taking such approach (having player's container with several sprites in it)?

Thank you in advance.


Garwin model in Pixijs?

$
0
0

Hello,

I've been trying to implement some simple physics simulation in pixi, involving a ball (circle) that bounces around and spins. I've managed to aproximate a pretty good model myself but the movement always becomes awkward when the ball begin to slow down so I tried to use the Garwin model I found here. However, something must be wrong with either the way I applied the functions or the MUs i'm using because as the ball settles to the floor it begins to accelerate exponentially.

 

This is my bounce function:

  let alfa = 0.4,
      cor = {
        x: 0.8,
        y: 0.8
      }

  cat.radius = 32;

  function enhancedBounce() {
    let vx = (((1 - (alfa * cor.x)) * cat.vx) + ((alfa * (1 + cor.x)) * cat.vr * cat.radius)) / (1 + alfa);
    let vr = ((1 + cor.x) * cat.vx + alfa * (1 + cor.x) * cat.radius * (cat.vr)) / (cat.radius * (1 + alfa));

    cat.vr = vr;
    cat.vx = vx;

    cat.vy = -cor.y * cat.vy ;
  }

Where cat.vx and cat.vy are velocity components and cat.vr is the angular velocity of the ball. Now I'm pretty bad at math but it seems that whatever I input into the functions as vx and vr, the output of both functions is greater than those values (vr' > vr and vx' > vr) which seems counterintuitive to me, however, since I'm not good enough at math I can't demonstrate that this is in fact the case. 

 

Any idea what i'm doing wrong?

The "Learn Pixi.js" book. TypeScript Port

$
0
0

This is an official link to original book examples: https://github.com/kittykatattack/learningPixi

I will public examples on:

  • Playground. You will be able to see a code and a result. I use complication to  AMD modules (Asynchronous Module Definition) and the RequireJS library to load AMD modules
  • GitHub Pages. I use compilation to CommonJS modules. I bundle JS files to bundle.min.js using Browserify and minify it to bundle.min.js using UglifyJS
  • Source code on GitHub: will be later

I will NOT use Webpack, Gulp, Grunt and so on. I will public the instruction on GitHub how to build examples locally in the README.md file.

Note. Release version is loaded more quickly, but on playground you can see a code, you can make a fork, change the code and save it with new link.

  1. Hello World: playground, release
  2. Displaying the canvas: playground, release

  3.  Sprite From Image: playground

Extending PIXI.utils

$
0
0

Are there some examples of extending PIXI.utils namespace?

Taking a look at Pixi's debugging and editor tools, the Free Transform Tool appears to extend PIXI.utils - cool library, looks pretty alpha without npm or webpack.  Just references PIXI in a global scope and attempts to prototype utils.

If I want to extend Pixi through utilities, or maybe just provide webpack module libraries through npm, any recommendations such as good example projects to follow?

Inconsistent availability of font for PIXI.Text

$
0
0

I have a bit of a head scratcher. I am using web fonts, which I load prior to starting. I've defined these as @font-face in the style tags. I include these in my assets folder with all my assets. I can verify via the Developer tools the font is indeed loaded.

I've noticed a strange behavior where the font is not always used. 

I am currently using Roboto as my standard font during prototyping. This is a sans-serif font. It seems that when I try and use a font that doesn't "exist", it defaults to a serif font which is probably Times Roman, as I'm testing on Chrome. So visibly, it is obvious when the text is Roboto versus Times Roman.

I've noticed that for certain text, it seems to use the default font versus Roboto. I've dumped out the text style and it's the same for the text. The TextStyle settings I set are fontFamily (Roboto), fontSize, fontStyle (always normal), fill, and align. I do sometimes set fontWeight (either normal or bold).

What is bizarre is that the exact same TextStyle will fail for some text. I've noticed in particular, numbers will fail. By fail I mean it ends up using the default font, Times Roman.

Another odd thing I noticed is the fontFamily should be "Roboto". In Chrome, if I use "Robots-Regular" everything will work. However, when I try and use this on iOS (Cordova), then it uses the default Times Roman.

Note usage of PIXI.Text doesn't matter. It's interleaved, but always the same items use the default. So I'm investigating it more for user error. But it seems very strange behavior that using Roboto-Regular versus Roboto will make it always work on Chrome (but then fail in iOS).

I'm trying to find in the pixi code where it makes the decision point on the font to see if I can at least try and better deduce why this is happening.

Where is glCore in PIXI v5? (pixi.js-legacy)

$
0
0

Howdy!

I am finally starting the process of upgrading to PIXI v5. I have a few custom renderers written in V4, and made use of glCore.GLShader, glCore.GLBuffer, and glCore.VertexArrayObject quite heavily. In V4, I could import glCore from `pixi.js` and have what I need. In V5, is glCore still packaged with PIXI? If it is, where can I find it? If it is no longer included, does V5 provide similar helper methods or objects to make building custom renderers easier? I am aware of the migration guide: https://github.com/pixijs/pixi.js/wiki/v5-Migration-Guide but it doesn't go very low-level.

 

Thanks!

Proper freeing of textures and cleaning up the loader

$
0
0

I have an in-game asset that can be swapped out. I want to do the right thing by loading the new asset on-demand and then be a good citizen and release the older textures.

Code looks something like the following:

// Purge old spritesheet
spritesheet = this._game.loader.resources[oldName].spritesheet;
if (spritesheet) {
    spritesheet.destroy();
}

I notice the side effect is the loader does not realize the sprite sheet has been destroyed. So once I try and re-use the original asset, it causes problems since I check for existence in the loader resources to see if I should reload the asset.

Most APIs I've worked with or built have texture systems which are independent of the loader and also clean up properly. So any query for the texture, once destroyed is consistent.

Has there been any thought of, instead of grabbing stuff from Loader's resources, having a TextureManager or SpritesheetManager (you actually could get away with just one which is what typically do)?

Anyways, what is my best way to handle this? Just set the entry to null?

Also, another question I had was related to PIXI.utils.TextureCache. I've found there are times I actually need to use PIXI.utils.TextureCache to find textures. I know it's not ideal and I think I read one shouldn't use it, but there are times I need to get a sub-texture but do not have the atlas name.

Oh, I tested and it does appear the TextureCache is actually cleaned up. 

same shader with different uniforms?

$
0
0

Hello! Loving v5 it's great!

I've been trying to render an extremely large map of tiles in smaller chunks that load in as the player moves around. I've done this with sprites and a render texture per chunk and it works fine, but now to learn some webgl I'm porting the project to use pixi Mesh + Shader.

I've gotten to the point where I have the vertices and uv coords for a 16x16 chunk of tiles (skipping the code, nothing special). I then create a mesh per chunk of tiles and position them around. Code looks like this:

const shader = PIXI.Shader.from(vertexSrc, fragmentSrc, uniforms);
const chunk = new PIXI.Mesh(geometry, shader); // etc for many chunks

and then I just change the chunk.x and chunk.y 

Now what I'm trying to do next is actually show different textures for each tile within each chunk, for which I'm using a collection of tileTypes which is either going to be an array or texture uniform with the data for the 256 tiles that comprise the 16x16 chunk. I hope that makes sense.

In any case, because all of the chunks have the same geometry and the same shader if i change the `chunk.shader.unforms.tileType` it changes all of the chunks at the same time. If I create a new shader for each chunk so they have a unique uniforms object each, it ends up being an expensive operation which creates a visual hitch. I could probably create a pool of meshes and shaders and reuse them such that I wouldn't have to actually create new shader objects at run time as chunks load into the game, but before going down that path I wanted to know if there was an easier way. Can I somehow create meshes that share the geometry, vertexShader, fragmentShader, but have a *unique* uniform per instance of the mesh?

 

Thanks :D


Layered backdrop JPG (with alpha mask) v png

$
0
0

Hi all, I have a backdrop for a little game that I'd like to split into layers (with some particles between)  nothing major probably 2-3 layers at max. 

The game is for mobile and file sizes have got to be as low as possible.  The backdrop in question is not something that can be tiled or recreated with an atlas so I'll need to split it into a few largish images.  png 32s' tend to be too heavy, 8 bit will probably lose too much colour information. 

I was wondering about instead using a larger jpg (eg the backdrop is 1920x1080)  but maybe extending it to a square 2k, then using that with alpha masks from (colourless pngs) as an alternative (if that makes sense). 

I thought this way I could drop the size of the jpg more without as much degradation as a png would have (& have finer control).  Hoping the colourless pngs wouldn't make as big of a hit essentially just being an alpha map..

Sounds a long way around a small problem, just theorizing atm & wondering if anyone had tried anything similar, noticed any peformance hits using masks v png or even found a nicer alternative?

Cheers for any advice!

How to create photoshop SABER plugin effect in PIXI?

$
0
0

I want to create a light trail effect of the border of the popup, the effect is similar to this:

I tried with rope + sprite animation, however, the glow around the texture will become very weird when the trail has a 90 degree turn

 

I heard that shader can handle something like this, but I have no idea how to do that

 

Anyone has a idea?

How to use PIXI import customizer with Typescript?

$
0
0

I'm trying to use this tool: http://pixijs.io/customize/But I'm having troubles with getting the types to be imported.

Could not find a declaration file for module '@pixi/constants'. '.../node_modules/@pixi/constants/lib/constants.js' implicitly has an 'any' type.
Try `npm install @types/pixi__constants` if it exists or add a new declaration (.d.ts) file containing `declare module '@pixi/constants';`
ts(7016)
 

Does anyone know how to solve this? I know that in the main pixi.js import, the types are already there.

I followed the tool and did this to get the modules:

npm install @pixi/constants @pixi/core @pixi/display @pixi/math @pixi/runner @pixi/settings @pixi/ticker @pixi/utils

Intermittent Global Text Offset

$
0
0

Hey all!  I'm using Pixi.js in my edutainment platform, and it rocks.  We're about to go live, and in our testing have found an intermittent issue with how text in Pixi.Text elements is rendered.

Context: we're using a webfont loaded using Google's webfont.js like so:

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
  WebFont.load({
    custom: {
      families: ['Short Stack']
    }
  });
</script>

This produces a synchronous load, and is run before we bootstrap up Pixi and our framework/game.  This seems to be working fine; I include it purely for context.

The problem is that very seldomly, our Pixi.Text elements render with the text offset vertically by ~5 pixels.  When this happens, ALL our text is offset.  Doing a hard refresh (ctrl+shift+R on Firefox) resolves the issue, usually.  See the attached screenshots for what it looks like when it borks.

So!  Any ideas what could be causing this issue?  I know folks have had issues with load timing in the past, but the webfont is clearly loaded by the time the game renders - the font is correct in both versions.  There's zero code changes between the working and offset versions - just a hard refresh.  Help?

 

frame2.png

frame1.png

Hitboxes

$
0
0

I have a Graphics object that I'm checking mouseover events on. When hovered over, I want the object to get larger and rotate itself, but I don't want the hitbox to change. I'm not really sure how to achieve this, because getBounds returns a rectangle and not a polygon or something like that.

Viewing all 3978 articles
Browse latest View live