pixi.js PIXI.Texture.from() can't add images - javascript

I'm using react with pixi.js to development a simple web game
and I want to add some images to pixi.js from local directory
here is the website I studied
https://pixijs.io/examples/#/demos-basic/container.js
and here are the codes
import * as PIXI from 'pixi.js'
import React from 'react'
export default class PixiTestPage extends React.Component{
componentDidMount(){
//Create a Pixi Application
const app = new PIXI.Application({
backgroundColor: 0x1099bb
});
//Add the canvas that Pixi automatically created for you to the HTML document
document.body.appendChild(app.view);
const texture = PIXI.Texture.from("./bunny.png")
const bunny = new PIXI.Sprite(texture);
bunny.anchor.set(0.5)
bunny.x = app.screen.width / 2;
bunny.y = app.screen.height / 2;
app.stage.addChild(bunny);
}
render(){
return (
<div>
</div>
)
}
}
but the browser keep showing error message
Uncaught (in promise)
same as I use #inlet/react-pixi
https://reactpixi.org/
import * as PIXI from 'pixi.js'
import React from 'react'
import { Stage, Sprite } from '#inlet/react-pixi';
export default class PixiTestPage extends React.Component{
componentDidMount(){
}
render(){
return (
<div>
<Stage>
<Sprite image="./bunny.png" x={100} y={100} />
</Stage>
</div>
)
}
}
the Uncaught (in promise) error still there
but when I using the url like
https://pixijs.io/examples/examples/assets/bunny.png
it worked
how to use images in pixi.js with local directory?
here is the image path
path

Oh I forgot react must use import images...
so the solution is
import React from 'react'
import { Stage, Sprite } from '#inlet/react-pixi';
import bunny from './bunny.png'
export default class PixiTestPage extends React.Component{
componentDidMount(){
}
render(){
return (
<div>
<Stage>
<Sprite image={bunny} x={100} y={100} />
</Stage>
</div>
)
}
}

Related

OnClick is not working, but no errors appear in the console

As I am currently learning React, I am creating a joke generator. I created a local file and was able to pull the data (jokes) and display it on the browser. Now, I am trying to create a button that when you click, it displays a random joke. I can see the joke and button, but no action is being triggered. I check the console and there are no errors. If I use onClick = {randomJoke}, then I get an error saying listener was expecting a function, not an object. Can someone point help me out and point out what is wrong?
This is how I currently have it set up:
import React from 'react'
import SportsJokesData from './SportsJokesData';
class SportsJokesApi extends React.Component {
constructor(props){
super(props);
this.getRandomJoke = this.getRandomJoke.bind(this);
}
getRandomJoke(){
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
}
render() {
const randomJoke = this.getRandomJoke()
return (
<React.Fragment>
<p> {randomJoke.question}</p>
<p>{randomJoke.answer}</p>
<button onClick={this.getRandomJoke}>
click here
</button>
</React.Fragment>
)
}
}
export default SportsJokesApi;
This is how the file was originally scripted prior to adding the button.
import React from 'react'
import SportsJokesData from './SportsJokesData';
class SportsJokesApi extends React.Component {
getRandomJoke(){
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
}
render() {
const randomJoke = this.getRandomJoke()
return (
<React.Fragment>
<p>{randomJoke.question}</p>
<h1>{randomJoke.answer}</h1>
</React.Fragment>
)
}
}
export default SportsJokesApi;
You cannot just return a new component on onClick event. You need to set some state first. This guide is useful: https://flaviocopes.com/react-show-different-component-on-click/
You need to re-render your React component, when there is a new joke. To do this store the randomJoke in the state of your React Component.
When you call this.getRandomJoke you should update the state along with it, so that a re-render of the React component is triggered. When this happens the UI will be updated with the latest value of the randomJoke
import React from 'react'
import SportsJokesData from './SportsJokesData';
const initialState = {
randomJoke: null
};
class SportsJokesApi extends React.Component {
constructor(props) {
super(props);
this.getRandomJoke = this.getRandomJoke.bind(this);
this.state = initialState;
}
getRandomJoke() {
this.setState({
randomJoke: SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
});
}
render() {
const { randomJoke } = this.state;
return (
<React.Fragment >
<p> {randomJoke.question} </p>
<p> {randomJoke.answer} </p>
<button onClick = {this.getRandomJoke}>click here </button>
</React.Fragment >
);
}
}
export default SportsJokesApi;

React Lazyload as soon as page interacted with

I'm building a React site which uses live chat and am using the react-livechat package. I've paired this up with the react-lazyload plugin to try to prevent it from adversely affect page load times.
I'm now trying to work out a way to load the livechat component in as soon as the page is interacted with. Currently it only renders when the page is scrolled to within a set distance of the component which by default is the footer of the page. This does prevent the page load being impacted but requires a user to scroll a certain distance before the component loads. Ideally it would load form any interaction with the page.
import React, { Component } from 'react';
import LiveChat from 'react-livechat';
import LazyLoad from 'react-lazyload';
class App extends Component {
render() {
return (
<div className="App">
...
<LazyLoad once>
<LiveChat license={'xxxxxx'} />
</LazyLoad>
...
</div>
);
};
}
export default App;
I managed to get this behavior with a workaround and loading the component after a certain period of time. I found that 10 seconds worked well to ensure even on mobile everything had entirely rendered.
// App.js
import React, { Component } from 'react';
import LazyLiveChat from './components/utils/lazyLiveChat';
class App extends Component {
constructor() {
super();
this.state = { loadLiveChat: false };
}
componentDidMount() {
setTimeout(() => this.setState({loadLiveChat: true}), 10000);
}
render() {
return (
<div className="App">
...
<LazyLiveChat loadChat={this.state.loadLiveChat} />
...
</div>
);
};
}
export default App;
// lazyLiveChat.js
import React, { Component } from 'react';
import LiveChat from 'react-livechat';
class LazyLiveChat extends Component {
render() {
if (this.props.loadChat) {
return (
<LiveChat license={xxxxxx} />
);
}
return null;
}
}
export default LazyLiveChat;

Rendering a canvas object received from props

Good day!
I am new to React and html2canvas. I am making an app which will take "screenshots" of my DOM using html2canvas then store it to an array of screenshots which will then be also rendered on the screen.
I am storing each <canvas> object received from the html2canvas promise to an array then pass it to my ScreenshotsContainer component which passes the array to the Screenshots component. The Screenshots component will then map the array of <canvas> objects to individual Screenshot components.
In App.js, I am calling the html2canvas function then pass the array to ScreenshotsContainer component
import React, { Component } from 'react';
import ScreenshotsContainer from './containers/ScreenshotsContainer/ScreenshotsContainer'
import html2canvas from 'html2canvas';
import './App.css';
class App extends Component {
state = {
canvasArray: []
}
getScreenshotHandler = () => {
console.log("[Canvas Array from state length:]" + this.state.canvasArray.length)
let canvasArray = this.state.canvasArray;
html2canvas(document.body).then((canvas) => {
canvasArray.push(canvas)
});
console.log("[Canvas Object value: ]" + canvasArray);
this.setState({ canvasArray: canvasArray })
}
render() {
return (
<React.Fragment>
<button onClick={this.getScreenshotHandler}>Get Screenshot</button>
<ScreenshotsContainer canvasArray={this.state.canvasArray} />
</React.Fragment>
);
}
}
export default App;
The ScreenshotsContainer component will pass the received array to the Screenshots component:
import React, { Component } from 'react';
import './ScreenshotsContainer.css'
import Screenshots from '../../components/Screenshots/Screenshots';
class ScreenshotsContainer extends Component {
render() {
return (
<div className="ScreenshotsContainer">
<Screenshots canvasArray={this.props.canvasArray} />
</div>
);
}
}
export default ScreenshotsContainer;
The Screenshots component will map the array and pass each canvas object to the Screenshot component:
import React, { Component } from 'react';
import Screenshot from './Screenshot/Screenshot';
class Screenshots extends Component {
render() {
const screenshots = this.props.canvasArray.map(canvas => {
return (
<Screenshot
key={Math.random}
canvasObj={canvas}
/>
)
})
return (
<React.Fragment>
{screenshots}
</React.Fragment>
);
}
}
export default Screenshots;
Here is the Screenshot component
import React from 'react';
import './Screenshot.css';
const screenshot = (props) => (
<div className="Screenshot" >
<canvas ref={props.canvasObj} style={{
width: '10%',
height: '10%'
}} />
</div>
);
export default screenshot;
What I actually get when pressing the button:
Actual screenshot of my result
I was wondering which part went wrong. Any help would be appreciated.
This particular library works in a specific way (looks like it's doing a lot of "magic" under the hood - you should look at the source code here more specifically the renderer folder inside src)
Saving the canvas to the state inside of an array (the correct react way of doing things) will be a problem as it saves it as a complex object with many methods etc... and we can not render objects... This lib was not written with React in mind...
The code sample below is a simple implementation in React...
Here is a live demo: https://codesandbox.io/s/9y24vwn1py
import React, { Component } from 'react';
import html2canvas from 'html2canvas';
class App extends Component {
constructor(props) {
super(props);
this.captureRef = React.createRef();
this.displayRef = React.createRef();
}
getScreenshotHandler = () => {
html2canvas(this.captureRef.current).then(canvas =>
this.displayRef.current.appendChild(canvas),
);
};
render() {
return (
<div>
<div ref={this.captureRef}>
<h2>This enitre div will be captured and added to the screen</h2>
</div>
<button onClick={this.getScreenshotHandler}>Get Screenshot!</button>
<section>
<h5>Your screenshots will be availbale below</h5>
<div ref={this.displayRef} />
</section>
</div>
);
}
}
export default App;
EDIT: based on the comment below here is yet another workaround:
class App extends Component {
constructor(props) {
super(props);
this.state = { canvasArray: [] };
this.captureRef = React.createRef();
}
getScreenshotHandler = () => {
html2canvas(this.captureRef.current).then(canvas =>
this.setState({
canvasArray: [canvas.toDataURL(), ...this.state.canvasArray],
}),
);
};
renderCanvas = () => {
return this.state.canvasArray.map((canvas, i) => {
return <img key={i} src={canvas} alt="screenshot" />;
});
};
render() {
return (
<div className="wrapper">
<div ref={this.captureRef}>
<p>This enitre div will be captured</p>
</div>
<button onClick={this.getScreenshotHandler}>Get Screenshot!</button>
<section>
<h5>Your screenshots will be availbale below:</h5>
{this.renderCanvas()}
</section>
</div>
);
}
}
Link to live demo: https://codesandbox.io/s/1r213057vq

_pixi2.default.Application is not a constructor?

When i am trying to integrate PIXIjs with Reactjs I was getting this error
pixi_loader.js?0eb2:5 Uncaught TypeError: _pixi2.default.Application is not a constructor
at eval (eval at
My Code
import React, { Component } from 'react';
import PIXI from 'pixi';
import three from '../../../assets/images/3.png';
import five from '../../../assets/images/5.png';
export class PixiLoader extends Component {
constructor(props){
const app = new PIXI.Application();
const graphics = new PIXI.Graphics()
.beginFill(0xFF0000)
.drawCircle(0, 0, 50);
const image = app.renderer.plugins.extract.image(graphics);
document.body.appendChild(image);
super(props)
}
render(){
return(
<div>
{'PIXI'}
</div>
);
}
}
export default PixiLoader;
I have followed this link to work it out.
http://pixijs.download/release/docs/PIXI.extract.html
import * as PIXI from 'pixi';
There is no default export in pixi
I have Solved it using require
let PIXI = require('pixi.js');`

Exporting functions with reactjs and babel

I have a project using reactjs, which is transpiled by babel. I use the es2015 and react transforms in my .babelrc. I am currently refactoring and in my first pass I basically did export class foo for everything I needed. A lot of these classes should really just be functions, so I am trying to rewrite them as such, but I keep getting the same error. My main application file looks somethings like this:
import React, { Component } from 'react';
import {Foo, Bar} from './components/ui.js';
class Application extends Component {
constructor(props){
super(props);
this.state = {
object: null
}
}
componentDidMount(){
// code
}
componentDidUpdate(){
// other code
}
render(){
return(
<div>
<Foo />
<Bar />
</div>
)
}
}
module.exports = Application
And my import from ui.js is like this:
import React, { Component } from 'react';
export class Foo extends Component {
constructor(props){
super(props);
}
render() {
return (
// Some JSX
)
}
}
export class Bar extends Component {
constructor(props){
super(props);
}
render() {
return (
// Some other JSX
)
}
}
When I try and change one of these exported classes to a function, for example:
// Note: I have tried a variety of syntax such as function, const, etc...
export var Bar {
render() {
return (
// Some other JSX
)
}
}
I get the following error:
SyntaxError: Unexpected token <line where I declare a function>
I am not sure what I am doing wrong, and my google searches are only coming up with answers to other problems.
It's the same as defining the function as a variable but just adding export to the front e.g. (using ES6 syntax)
export const render = () => (
// Some other JSX
);
or alternatively
export var render = function() {
return (
// Some other JSX
);
};
Exporting functions is no different than exporting class. Basic rules must be followed .
Function/Class name should in CAPS
There will be only one "export" line .
Every function return body should have a single tag encompassing other parts. Most commonly used is a tag .
This usually works: import App from "./App"; where App.js is my jsx file.
You can do an explicit import too . : import AllApp from "./classhouse.jsx";
Name of the js/jsx file does not matter. It can be anycase (lower, upper).
For returning multiple functions from one file, you need to create one more function , that encompasses all other functions .
See the example below showing multiple functions returned.
import React from 'react';
/* All function / class names HAS TO BE in CAPS */
var App1 = function (){
return (
<div>
<h1>
Hello World
</h1>
</div>
)
}
var App2 = function (){
return (
<div>
<h1>World Number 2 </h1>
</div>
);
}
var AllApp = function (){
return (
<div>
<App1 />
<App2 />
</div>
);
}
export default AllApp;
My index.js file:
import React from 'react';
import ReactDOM from "react-dom";
import AllApp from "./classhouse.jsx"; /* Note: App name has to be in CAPS */
import App from "./App";
const jsx =
<div>
<AllApp />
<App />
</div>
ReactDOM.render(jsx, document.getElementById("root"));
You are writing functional components in wrong way.
function Welcome() {
return <h1>Hello World</h1>;
}
or
const Welcome = () => {
return <p>Hello Wrold</p>
}
export default Welcome ;
ES6 doesn't allow export default const. You must declare the constant first then export it.

Categories

Resources