Coder Social home page Coder Social logo

expo-pixi's Introduction

expo-pixi

Tools to use Pixi.js in Expo!

To get started: yarn add expo-pixi in your Expo project and import it with import ExpoPixi from 'expo-pixi';.

Side-Effects

To use Pixi.js with Expo & React Native you will want to import a modified version of Pixi.js like so:

// ✅
import { PIXI } from 'expo-pixi';

// ❌
import * as PIXI from 'pixi.js';

Now you can create a new Application the way you would on the web, but be sure to pass in a WebGLRenderingContext.

// ✅
const app = new PIXI.Application({ context });

// ❌
const app = ExpoPIXI.application({ context });

Finally, because of the way React Native currently works you must load in assets asynchronously.

/*
 * Accepts: 
 * - Expo.Asset: import { Asset } from 'expo-asset'; Asset.fromModule( ... );
 * - URL (with file extension): 'http://i.imgur.com/uwrbErh.png'
 * - Static Resource: require('./icon.png')
 */

// ✅
const sprite = await PIXI.Sprite.fromExpoAsync('http://i.imgur.com/uwrbErh.png');

// OR 

const texture = await PIXI.Texture.fromExpoAsync('http://i.imgur.com/uwrbErh.png');

// ❌
const sprite = await ExpoPIXI.spriteAsync('http://i.imgur.com/uwrbErh.png');

// OR 

const texture = await ExpoPIXI.textureAsync('http://i.imgur.com/uwrbErh.png');

Using web syntax will return a Promise, and throw a warning. It's bad practice, but if the asset is loaded already, this will work without throwing a warning.

const sprite = await PIXI.Sprite.from(require('./icon.png'));

// > console.warning(PIXI.Sprite.from(asset: ${typeof asset}) is not supported. Returning a Promise!);

// OR 

const texture = await PIXI.Texture.from(require('./icon.png'));

// > console.warning(PIXI.Texture.from(asset: ${typeof asset}) is not supported. Returning a Promise!);

Functions

ExpoPixi.application(props): PIXI.Application

Deprecated: Use new PIXI.Application({ context });

A helper function to create a PIXI.Application from a WebGL context. EXGL knows to end a frame when the function: endFrameEXP is called on the GL context.

context is the only required prop.

Learn more about PIXI.Application props

ExpoPixi.textureAsync(resource: any): Promise

Deprecated: Use PIXI.Texture.fromExpoAsync(resource);

ExpoPixi.spriteAsync(resource: any): Promise

Deprecated: Use PIXI.Sprite.fromExpoAsync(resource);

a helper function to resolve the asset passed in. textureAsync accepts:

You cannot send in relative string paths as Metro Bundler looks for static resources.


ExpoPixi.sprite({ localUri: string, width: number, height: number }): PIXI.Sprite

Deprecated: Use PIXI.Sprite.from(resource);

ExpoPixi.texture({ localUri: string, width: number, height: number }): PIXI.Texture

Deprecated: Use PIXI.Texture.from(resource);

Pixi.js does a type check so we wrap our asset in a HTMLImageElement shim.

ExpoPixi.Sketch

A component used for drawing smooth signatures and sketches.

See the sketch example on how to save the images!

Notice: the edges and ends are not rounded as this is not supported in PIXI yet: Issue

Props

Property Type Default Description
strokeColor number 0x000000 Color of the lines
strokeWidth number 10 Weight of the lines
strokeAlpha number 1 Opacity of the lines
onChange () => PIXI.Renderer null Invoked whenever a user is done drawing a line
onReady () => WebGLRenderingContext null Invoked when the GL context is ready to be used

ExpoPixi.FilterImage

A Image component that uses PIXI.Filter

Props

Property Type Default Description
resizeMode string null Currently only supports cover, and contain
filters Array<PIXI.Filter> null Array of filters to apply to the image
source number, string, Expo.Asset null Source can be a static resource, image url (not {uri}), or an Expo.Asset

Example

Snack

import React from 'react';
import Expo from 'expo';
import { PIXI } from 'expo-pixi';

export default () => (
  <Expo.GLView
    style={{ flex: 1 }}
    onContextCreate={async context => {
      const app = new PIXI.Application({ context });
      const sprite = await PIXI.Sprite.fromExpoAsync(
        'http://i.imgur.com/uwrbErh.png',
      );
      app.stage.addChild(sprite);
    }}
  />
);

NPM

expo-pixi's People

Contributors

0xclpz avatar aasfga avatar dependabot[bot] avatar evanbacon avatar ide avatar pieterbeulque avatar tsapeta avatar wkozyra95 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

expo-pixi's Issues

Fatal crash after waking up.

Hello,

This is my first post, so please let know if I am not providing with enough information with the issue.

I have developed an app that uses expo-pixi to capture a user signature. I recently noticed that when the device timeout while ExpoPixi.Sketch is displayed, after waking up and if the user press the android "overview" button... The app will immediately crash. This can only be reproduced via Expo XDE with "Development Mode" OFF, or an install on the device.

After some investigations, I was able to capture the fatal error via Fabric, and it seems to have something to do w/ destroying the GLView context.
Fatal Exception: java.lang.RuntimeException Unable to stop activity {com.pixi-test/host.exp.exponent.experience.ShellAppActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.lang.Thread.interrupt()' on a null object reference

Here is the full dump from Fabric for anyone who is interested.
fabric-dump.txt

Also, I think this problem might be OS specific because I cannot reproduce it on my phone (Android 8.1.0). I have only been able to reproduce this on devices with (Android 7.0).

{ "dependencies": { "expo": "^28.0.0", "expo-pixi": "^0.2.4", "react": "16.3.1", "react-native": "https://github.com/expo/react-native/archive/sdk-28.0.0.tar.gz" } }

I have created a simple test app for reference.
https://github.com/alaconda/pixi-test

Thanks in advance for your help. Please let me know if you need any additional information.

Pixi is not working on Android with SDK29.0.0

I got the following error message

[Unhandled promise rejection: Error: unexpected url: file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540rustykey%252Fexpo-pixi/5EOyTDQ.jpg]

I think that accessing a file in cache has a problem.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Expo from 'expo';
import ExpoPixi from 'expo-pixi';
export default class App extends React.Component {
  render() {
    return (
      <Expo.GLView
        style={{ flex: 1, width:300, height:300 }}
        onContextCreate={async context => {
          const app = ExpoPixi.application({ context });
          const sprite = await ExpoPixi.spriteAsync(
            'https://i.imgur.com/5EOyTDQ.jpg',
          );
          app.stage.addChild(sprite);
        }}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Can't find variable asset

When ExpoPixi is imported, this error occurs

import ExpoPixi from 'expo-pixi';

screenshot_1518893033

Do I forget something in packages.json?

package.json

    "EventEmitter": "^1.0.0",
    "expo": "^25.0.0",
    "expo-asset-utils": "^0.0.4-alpha.0",
    "expo-pixi": "^0.2.1",
    "frisbee": "^1.6.4",
    "path": "^0.12.7",
    "pixi-filters": "^2.5.1",
    "pixi.js": "^4.7.0",
    "react": "16.2.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-25.0.0.tar.gz",
    "react-native-country-picker-modal": "^0.5.1",
    "react-native-elements": "^1.0.0-beta2",
    "react-native-form": "^2.1.2",
    "react-native-loading-spinner-overlay": "^0.5.2",
    "react-native-mentions": "^1.1.4",
    "react-navigation": "^1.0.0-beta.27",
    "url": "^0.11.0"

eraser

how can i remove with eraser ?

Cant install

Im getting this error.

C:\Users\user\Documents\PONS FILES\WORK\JONATHAN\UOB-SUMMIT\node_modules\@expo\browser-polyfill: Command failed.
Exit code: 2
Command: find ../ -name .babelrc -delete
Arguments:
Directory: C:\Users\user\Documents\PONS FILES\WORK\JONATHAN\UOB-SUMMIT\node_modules\@expo\browser-polyfill

Environment
- "expo": "^29.0.0",
- "react": "16.3.1",
- "react-native": "https://github.com/expo/react-native/archive/sdk-29.0.0.tar.gz",
- node: 8.9.0
- yarn : 1.3.2

FilterImage doesn't work with ImagePicker

ExpoPixi.FilterImage don't work with localUri (file://) that's coming from Camera! I try with {uri} or direct with string link but none of both works! I have an error like

"Could not find image file:///var/mobile/Containers/Data/Application/5DC0A462-A09B-4EB1-9CE9-CF12E53A93F5/Library/Caches/ExponentExperienceData/%2540anonymous%252Fapp-f6e1550f-8652-48a2-b465-3222938fc807/16D1E15D-6EEA-4E68-BAFD-0FD52DBC97E8.jpg"

Adding Text

Hi I'm having an issue, not sure if it's me or a bug but thought I would ask here...

I'm trying to add text to ExpoPixi.Sketch like this:
var text = new PIXI.Text('this is the sample text');

this.sketch.stage.addChild(text);

getting an error
i.scale is not a function. (In 'i.scale(this.resolution, this.resolution)', i.scale is undefined

Thanks!

breaking after upgrade to expo sdk 26

I get this error when trying to import expo-pixi. It appears to work with the previous version of expo, but I would like to utilize expo 26's blob feature for uploading to firebase.

/Users/eli/code/streamplace/node_modules/gl-matrix/dist/gl-matrix.js: Couldn't find preset "es2015" relative to directory "/Users/eli/code/streamplace/node_modules/gl-matrix"

ABI25_0_0RCTFBQuickPerformanceLoggerConfigureHooks
ABI26_0_0RCTFBQuickPerformanceLoggerConfigureHooks
<redacted>
<redacted>
<redacted>
<redacted>
<redacted>
CFRunLoopRunSpecific
GSEventRunModal
UIApplicationMain
Exponent
<redacted>

Have tried adding babel-preset-2015. The error goes away, but otherwise does not fix anything

Cannot debug when Expo.Pixi.Sketch component is mounted

Hi, I'm looking for some help. I am using this in a CRNA app with Expo. Whenever I enable remote debugging when the <Sketch/> component is mounted, I get the following error:

Cannot read property 'x' of undefined

Object.onPanResponderMove
Sketch.js:86:15

I have so far been able to kind-of-sort-of work around this using some logging to figure out what's happening but my app has since gotten a little more complicated and it's no longer time-efficient to use logging.

I wanted to see if this is a known issue and whether there's a fix in the pipeline or a known fix? I'd be happy to submit a PR but I wanted to get some understanding of whether this is a fix that needs to happen within this project or the Pixi.js project before I started trying to get something working.

Unable to resolve "./textureAsync" from "node_modules/expo-pixi/lib/spineAsync.js"

I run into this error when trying to get the basic example to work. My project info:

"react": "16.5.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
"expo": "^32.0.0",
"expo-asset-utils": "^1.0.0",
"expo-pixi": "^1.0.0",

I think the bug is in this file:

expo-pixi/lib/spineAsync.js

in line 4,

import textureAsync from './textureAsync';

where I cannot find any file named as "textureAsync".

Please fix it.

snack doesn't work

The snack complains about expo-pixi not installed etc.

Should it work ?

FilterImage shows picture sideways

When replacing an Image component that displays properly with a FilterImage component with same props and settings, it shows the image sideways and stretched. The FilterImage/Image has a flex style within the parent component and is set to resizeMode 'cover'. Attached is what it looks like on the device. First is with Image component, second with FilterImage.

img_0499

img_0498

NPM Package out of date

NPM package is out of date, takeSnapshotAsync method is not included in Sketch component.

Can't get example to work

I have had no luck getting the example to work, any guidance is appreciated. Steps I followed:

expo init example && cd example
yarn add expo-pixi
yarn start

package.json dependencies:

  "dependencies": {
    "expo": "^32.0.0",
    "expo-pixi": "^0.3.2",
    "react": "16.5.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz"
  },

the error I get:

TypeError: undefined is not an object (evaluating '_expo.default.GLView')

This error is located at:
    in _default (at withExpoRoot.js:22)
    in RootErrorBoundary (at withExpoRoot.js:21)
    in ExpoRootComponent (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)
* App.js:6:8 in _default
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:10865:22 in mountIndeterminateComponent
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14091:21 in performUnitOfWork
- ... 17 more stack frames from framework internals

My App.js is copy-pasted from the example

import React from 'react';
import Expo from 'expo';
import ExpoPixi from 'expo-pixi';

export default () => (
  <Expo.GLView
    style={{ flex: 1 }}
    onContextCreate={async context => {
      const app = ExpoPixi.application({ context });
      const sprite = await ExpoPixi.spriteAsync(
        'http://i.imgur.com/uwrbErh.png',
      );
      app.stage.addChild(sprite);
    }}
  />
);

Is this an error on my part or is there something wrong here? Thanks

Edit: Have not resolved this yet sorry gave up for the meanwhile (1-25-19)

It doesn't display the component

Hello, I've been trying to have this to work with create-react-native-app, but it doesn't show anything. I don't know if this have anything to do with react-navigation or using npm instead of yarn ... Everything is updated, and I've tried to run both on simulator and on my SM-610M.

Code:

import React from 'react';
import ExpoPixi from 'expo-pixi';
import { View, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#795548',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

const Home = () => (
  <View style={styles.container}>
    <ExpoPixi.Sketch
      style={[styles.signature, { backgroundColor: 'white' }]}
      strokeColor="black"
      strokeWidth={6}
      transparent={false}
    />
  </View>
);

Screenshot:
image

PS: I've deleted gl-matrix/.babelrc as well

Video as a texture?

Hiya - do you know if it's possible to have a video element as a texture ?!

ImageFilter is not showing

Image Filter is not working

<ExpoPixi.FilterImage
            source={img}
            resizeMode="contain"
            style={styles.image}
            filters={filter}
          />

sdk : 30.0.0\

How do I save filtered images...?

Literally, how do I save those filtered images...?
Tried finding the source, no luck yet.
If any helpful resources, please redirect me.

Thank you,

Unable to resolve "./texture" pixi 1.0.1

Hi!

We've found a problem after installing pixi 1.0.1 with expo 31.0.2.

The complete error is:
Unable to resolve "./texture" from "node_modules\expo-pixi\lib\ExpoPixi.js"

Do you have any idea about this? Many thanks

`import ExpoPixi from 'expo-pixi';

render:
<ExpoPixi.Signature
ref={'signatureCanvas'}
style={common.sketch}
strokeColor={'blue'}
strokeAlpha={0.1}
strokeWidth={0.1}
onReady={this.onReady}
/>

`

undefined is not an object (evaluating 'window.emitter.emit') in Andriod

  • expo 25.0.0
  • expo-pixi 0.2.2
  • Android 7.1.1
  • iOS is OK
  "dependencies": {
    "expo": "^25.0.0",
    "expo-pixi": "0.2.2",
    "react": "16.0.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-25.0.0.tar.gz"
  },

Also happen when run examples/basic with expo-pixi 0.2.2
or just import ExpoPixi from 'expo-pixi'; in other project

https://i.imgur.com/p4I8MEP.jpg

Cannot read property of '0' in Expo-pixi

I hope it'll benefit others too.

I've a sample code adapted from https://github.com/expo/expo-pixi/blob/master/examples/filter-image/App.js,

I tried running this code on Snack and its working but as soon as I try to run it in my remote environment, it isn't working. It gives an error: "Cannot read property '0' of undefined".

I tried to debug the problem by trial and error and found that this something related to this chunk:

<ExpoPixi.FilterImage
            source={require('./assets/kylie.png')}
            resizeMode={'cover'}
            style={styles.image}
            filters={filter}
 />

When every I try to add the styles esp. the width and height, the red box popups every time giving above error.
image

Invalid image tag error in IOS

 const uri = await Expo.takeSnapshotAsync(
                  this.sketch,
                  options
                );

When i pass the uri in ImageStore.getBase64ForTag

 ImageStore.getBase64ForTag(
      this.state.imagePath,
      data => {
        console.log(data)
        const {
          id: user_event_id,
          event_id,
          event_batch_id,
          class_schedule_id
        } = this.state;
        const payload = {
          user_event_id,
          event_batch_id,
          event_id,
          class_schedule_id,
          signature: data
        };
        this.signAttendance(payload);
        ImageStore.removeImageForTag(this.state.imagePath);
      },
      e => console.warn("getBase64ForTag: ", e)
    );

Im getting this error

getBase64ForTag: , Object {
  "code": "EABI29_0_0RCTERRORDOMAIN0",
  "domain": "ABI29_0_0RCTErrorDomain",
  "message": "Invalid imageTag: file:///Users/nemy/Library/Developer/CoreSimulator/Devices/439F2728-B43A-462E-AC77-025BBC65B07E/data/Containers/Data/Application/CF2E758E-DC5C-47A8-A2C5-408CE8D27C3D/Library/Caches/ExponentExperienceData/%2540anonymous%252Fuobsummit-0bbf16e3-fb09-45d8-9b99-a5bb6b36141b/ViewShot/52B06BD4-82F7-4FFF-94C9-D47A07D01F4A.png",

Touch events not triggered on Sprite

Hi there, I'm able to render a sprite, adjust rotation etc, however I'm not able to receive any touch events on the sprite.

...
sprite.interactive = true;
sprite.on("pointerdown", () => { 
  console.log("touch");
})

Is there another sprite property that I need to set, other than interactive?

I've also tried other event names tap, touchstart etc, however none of these work.

Thanks for any help.

Animating the filterImage

I've been trying to animate a filter to see the performance on mobile using requestAnimationFrame but doesn't seem to work. The app crashes and doesn't log properly.

I tried code like this:

animate(){
    console.log('animate');
    myFilter.angle += Math.cos(Date.now()*0.001);
    console.log( this.filteredImage === undefined );
    if( this.filteredImage ){
      console.log( this.filteredImage.renderer );
    }
    // this.filteredImage.renderer._update();
    requestAnimationFrame(this.animate.bind(this));
  }
  render() {
    const filter = this.filters[this.state.index];
    return (
      <View style={styles.container}>
        <TouchableOpacity
          style={styles.touchable}
          onPress={() => {
            const index = (this.state.index + 1) % this.filters.length;
            this.setState({
              index,
            });
          }}>
          <ExpoPixi.FilterImage
            ref={ el => this.filteredImage = el }
            source={require('./assets/kylie.png')}
            resizeMode={'cover'}
            style={styles.image}
            filters={myFilter}
          />
        </TouchableOpacity>
      </View>
    );
  }

Beside the animate function stop logging, doesn't look I can access the renderer from the parent component.

FilterImage resizeMode doesn't work

I am using FilterImage to adjust Brightness of image.
Here is my code:
<FilterImage
source={this.state.image?{uri:this.state.image.uri}:require("./assets/flowers.png")}
resizeMode='cover'
style={{
width: '90%',
height: '90%',
backgroundColor: "transparent",
}}
filters={filter}
/>

I chose image from iCloud using DocumentPicker and set image state.
When I change image, resizeMode didn't work.
I think it is side-effect.

I attached 2 screenshots.
img_0562
img_0563

ExpoPixi.Sketch drawing over the edges cause incorrect drawing on android

Hi,
There is a bug when drawing and reaching the edges(every edge except the bottom edge) -the drawing goes crazy.
For example, in the screenshot below I tried to draw a line form right to left but when I got near the left edge the line automatically was drawn to bottom edge.

Tested on Lg g4(Marshmallow) and galaxy s7 (nougat), in IOS everything works.

whatsapp image 2018-06-04 at 14 29 20

The code:

    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' , backgroundColor: 'red'}}>
            <ExpoPixi.Sketch
              style={[styles.signature, { backgroundColor: 'white' }]}
              strokeColor={'black'}
              strokeWidth={6}
              transparent={false}
            />
      </View>
    );

Issue with PIXI filters evaluating undefined.__filters

On iOS my app is blowing up on this line in the PIXI filters package:

Object.assign(PIXI.filters, this.__filters);

The author is obviously expecting this to resolve to window or global, but in React Native it appears to be undefined.

Commenting put the lines that import pixi-filters fixes the issue:

import * as filters from 'pixi-filters';
PIXI.filters = { ...(PIXI.filters || {}), ...filters };

Anyone know a workaround for 'this'?

img_1453

First line drawn with ExpoPixi.Sketch is not captured?

Hi everyone! Great library that solves a real pain point - great stuff!

I almost have a nice little signature capture working.. however the first line drawn is not recorded in this.sketch.lines even though it shows in the Sketch component. The onChange function is not even fired.

I'm re-using your code @EvanBacon from your very useful article.

I would appreciate any help from anyone who has faced the same issue!

This is my component:

import Expo from 'expo';
import React from 'react';
import { Image, View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import ExpoPixi from 'expo-pixi'
import config from '../config';

export default class SignatureBox extends React.Component {

	constructor(props) {
		super(props);

		this.state = {
		};
	}

	onChange = () => {
		  for (let line of this.sketch.lines) {
		    console.log(line.points)
		  }
	}

	render() {

		return (

			<View style={styles.container}>
				<ExpoPixi.Sketch
				  ref={ref => (this.sketch = ref)}
				  style={styles.sketch}
				  strokeColor={'black'}
				  strokeWidth={5}
				  strokeAlpha={1}
				  onChange={this.onChange}
				/>
			</View>

		);
	}
}

Unable to resolve module `expo-asset-utils`

I'm getting the error in the tile above when trying to import ExpoPixi from 'expo-pixi';

I've tried clearing watchman cache and deleting the node modules directory with no result. Older version of this package install fine but do not work when trying to draw a signature.

I'm running the following versions in my package.json file

"expo": "^31.0.4",
"expo-pixi": "^1.0.0",
"native-base": "^2.9.2",
"react": "16.5.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-31.0.1.tar.gz",```

Thank you.

import ExpoPixi from 'expo-pixi'; is not working.

Hello, thank you for this wonderful library.
After I yarn add expo-pixi, I put import ExpoPixi from 'expo-pixi'; to a simple js and not using it, and it breaks.
Showing me this error
image
Then I go to my node_modules/expo-pixi, there is no sub node_modules folder in it, only the source code.
So I want to ask that should I install the dependencies that expo-pixi using to get it to work?
Thank you for seeing my questions!

Draw on picture

Hi,

I would like to use ExpoPixi.Sketch component to be able to draw on existing picture. I don't figure out how to passe an uri to the component (like in FilterImage case)

Maybe through onReady() ? Is it possible ?

Thanks a lot

Invalid pixed data argument for gl.textImage2D

Invalid pixed data argument for gl.textImage2D

image

Calling this.sketch.renderer._update() after this.graphics.clear()

import React, { Component } from 'react';
import { takeSnapshotAsync, GLView } from 'expo';
import {PIXI , Sketch} from 'expo-pixi';
import { Button, Platform, AppState, StyleSheet, View, ImageBackground, PixelRatio } from 'react-native';
import Splash from './../assets/splash.png';
import TouchableView from './TouchableView';

const isAndroid = Platform.OS === 'android';
const strokeColor = 0x0000ff
const strokeWidth = 10
const strokeAlpha = 1
const scale = PixelRatio.get();

function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

function scaled({ x, y }) {
  return { x: x * scale, y: y * scale };
}



export default class App extends Component {
  state = {
    image: null,
    appState: AppState.currentState,
  };

  handleAppStateChangeAsync = nextAppState => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      if (isAndroid && this.sketch) {
        this.setState({ appState: nextAppState, id: uuidv4() });
        return;
      }
    }
    this.setState({ appState: nextAppState });
  };

  componentDidMount() {
    AppState.addEventListener('change', this.handleAppStateChangeAsync);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this.handleAppStateChangeAsync);
  }

  onTouchesBegan = ({x, y}) =>  {
    this.graphics = new PIXI.Graphics()
    
    this.graphics.lineStyle(10, 0x000000, 10);
    this.x = x;
    this.y = y;
    this.graphics.drawRect(this.x, this.y,  1, 1);
    this.sketch.stage.addChild(this.graphics);
  }
  onTouchesMoved = ({x, y}) =>  {

    let width = x - this.x
    let height = y - this.y
    this.graphics.drawRect(this.x, this.y,  width, height);
  }
  onTouchesEnded = ({x, y}) =>  {

    let width = x - this.x
    let height = y - this.y

    this.graphics.clear()
    this.graphics.drawRect(this.x, this.y,  width, height);
  }
  onTouchesCancelled = ({x, y}) =>  {
  
  }
  

  onChangeAsync = async () => {
    const uri = await takeSnapshotAsync(this.image, {
        format: 'png'
    });
    this.setState({
      image: { uri },
    });
  };
  

  onReady = () => {
    this.sketch.renderer.transparent = true;
    this.sketch.renderer._update();
  };

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.container}>
            <View style={styles.sketchContainer}
            collapsable={false}
            ref={imageBackground => (this.image = imageBackground)}>
                <ImageBackground source={Splash} style={{height: '100%', width: '100%'}}
                imageStyle={{resizeMode: 'contain'}}>
                  <TouchableView
                    id="pixi-view"
                    style={{ flex: 1, backgroundColor: 'transparent' }}
                    onTouchesBegan={({ locationX: x, locationY: y }) => this.onTouchesBegan(scaled({ x , y }))}
                    onTouchesMoved={({ locationX: x, locationY: y }) => this.onTouchesMoved(scaled({ x , y }))}
                    onTouchesEnded={({ locationX: x, locationY: y }) => this.onTouchesEnded(scaled({ x , y }))}
                    onTouchesCancelled={({ locationX: x, locationY: y }) =>
                    scaled({ x, y })
                    }>
                    <Sketch
                      ref={ref => (this.sketch = ref)}
                      style={styles.sketch}
                      strokeColor={strokeColor}
                      strokeWidth={strokeWidth}
                      strokeAlpha={strokeAlpha}
                      onChange={this.onChangeAsync}
                      onReady={this.onReady}
                      />
                  </TouchableView>
                </ImageBackground>
            </View>
        </View>
        <Button
          color={'blue'}
          title="undo"
          style={styles.button}
          onPress={() => {
            this.sketch.undo();
          }}
        />
        <Button
          color={'red'}
          title="update"
          style={styles.button}
          onPress={() => {
            this.sketch.renderer._update();
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  sketch: {
    flex: 1,
    backgroundColor: 'rgba(255, 255, 255, 0)'
  },
  sketchContainer: {
    height: '90%'
  },
  image: {
    flex: 1,
    width: '100%',
    height: '100%'
  },
  label: {
    width: '100%',
    padding: 5,
    alignItems: 'center',
  },
  button: {
    // position: 'absolute',
    // bottom: 8,
    // left: 8,
    zIndex: 1,
    padding: 12,
    minWidth: 56,
    minHeight: 48,
  },
});

standalone application crashes with Invalid pixel data argument for gl.texImage2d()

Platform: Android
Expo version: 32.0.0
Expo cli version: 2.11.8
app run in expo client and stand alone

I've created a stand-alone app for Android that loads a series of png files into sprites. The application always works using the Expo client, and initially works when deployed as a stand-alone app, but after a day or so, the standalone app starts failing with "Invalid pixel data argument for gl.texImage2d()"

The code used to load the image:

let ballSprite = await PIXI.Sprite.fromExpoAsync( require("../assets/images/b3.png") )

I've tried to preload the assets in the App.js with:

Asset.loadAsync([
....
require('./assets/images/b1.png'),
....
]),

I've defined the asset bundle pattern in the app.js
{
expo: {
...
"updates": {
"enabled": true,
"checkAutomatically": "ON_LOAD",
"fallbackToCacheTimeout": 300000
},
"assetBundlePatterns": [
"**/",
"./assets/images/
.png"
],
...
}
}

What's concerning is that the app just started failing after having been released for a couple of days. I've tried using some of the old patterns for downloading the assets and manually creating the HTMLImageElement to generate the Sprite, and although the techniques still work with the app when loaded in the Expo client, the stand-along app crashes.

I then changed the images completely and everything worked again. Then after about 15 hours the app started failing again with the same error. Could this be some side effect of accessing the CDN a stand-alone app? Nothing locally is being updated and yet the behavior of the app is changing.

Thank you for putting together such a fantastic integration with Pixi.

unexpected tail on my android phone

When I draw a signature, very thin dot line apper from (0,0) to last point.
I tested on several devices, but this issue happen on only this device.

I hope to fix this issue.
pixi

FilterImage not accepting uri in as source

WIth the ExpoPixi.FilterImage component, I can use a local image and require it as a source to use filters. However, I am unable to use a uri as the source even though I can in a regular Image react native component

Warning after adding expo-pixi library

Hi,

After running yarn add expo-pixi and restarting the app with yarn start, the app displays the following warning:

Unhandled promise rejection: Error: Font with family name '1E1C149B-2A6D-4FAF-93A9-B0B4DDA0140C-ionicons' already loaded
Stack trace:
  node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:146:41 in createErrorFromErrorData
  node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:95:55 in <unknown>
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:397:4 in __invokeCallback
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:127:28 in <unknown>
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:297:10 in __guard
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:126:17 in invokeCallbackAndReturnFlushedQueue

And if I am using ExpoPixi.FilterImage tag, I am getting an error saying undefined is not an object (evaluating 'Constants.manifest')

I am using sdk 32.0.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.