Code Monkey home page Code Monkey logo

pixi-text-input's Introduction

PIXI.TextInput - Plugin for pixi.js

About

This plugin for pixi.js provides a convenient way of adding text inputs to the pixijs-stage. The input itself is a HTML <input> element, which is positioned above the stage according to the transformation given by the PIXI-DisplayObject. The box is drawn on the PIXI-stage. Additionally, you can choose whether the plugin should substitute the <input> with a native pixi-Text when the textfield has no focus.

Demos

Demo with default box generator

Demo with custom box generator

Installing

Include thedist/PIXI.TextInput.min.js in your html document after pixi.js or install the npm package via: npm install pixi-text-input

Documentation

The TextInput behaves just like any other PIXI-DisplayObject. It inherits from PIXI.Container and has all the associated properties like width, height, rotation, scale ,alpha, etc.

Creating an instance

new PIXI.TextInput( { input: {...}, box: {...} } )

input : object

The css style attributes for the HTML input tag.

box : object | function

Either an object describing the style of the box using the default box generator, or a function which returns your own custom generated box.

Styling the input

You can apply any CSS styles. You have to use the camcelCase property names, though.

new PIXI.TextInput({
    input: {
        fontSize: '25pt',
        padding: '14px',
        width: '500px',
        color: '#26272E'
    }, 
    box: {...}
})

If you plan to use more advanced properties like text-shadow, you will have to disable substituteText, as their translation to the pixi-Text style is not supported, yet.

Box styling using the default box generator

The input can have 3 different states: DEFAULT, FOCUSED and DISABLED.

For each state you can apply a different style to the input-box. When passing the following object to the second parameter of the constructor...

new PIXI.TextInput({
    input: {...},
    box: {
        default: {fill: 0xE8E9F3, rounded: 16, stroke: {color: 0xCBCEE0, width: 4}},
        focused: {fill: 0xE1E3EE, rounded: 16, stroke: {color: 0xABAFC6, width: 4}},
        disabled: {fill: 0xDBDBDB, rounded: 16}
    }
})

...you will get a box-style as shown in this demo.

If you don't want a different style for each state, you can just pass:

new PIXI.TextInput({
    input: {...}, 
    box: {fill: 0xE8E9F3, rounded: 16, stroke: {color: 0xCBCEE0, width: 4}}
})

and have the same style for all 3 states.

Possible attributes
fill The fill color of the box
rounded The border-radius
stroke.color the color of the stroke
stroke.width the width of the stroke
stroke.alpha the alpha of the stroke

Box styling using a custom generator

Write your own function to generate the box.

function generateCustomBox(width, height, state){
    var box = new PIXI.Graphics()

    // draw the box based on width, height and the state (DEFAULT, FOCUSED or DISABLED)

    return box
}

then use it as follows

 new PIXI.TextInput({ input: {...}, box: generateCustomBox })

See this demo.

Reference

All described members & methods are accessible through an instance of the TextInput.

var input = new PIXI.TextInput({
    input: {fontSize: '25px'}, 
    box: {fill: 0xEEEEEE}
})
input.x = 100
input.y = 100
input.placeholder = 'Enter your Text...'
stage.addChild(input)
input.focus()

Members

substituteText : boolean

Whether the plugin should substitute the html input tag with a pixi-Text DisplayObject when there's no focus.

The plugin tries its best to mimic the exact look of the html input element, however with certain fonts/styles there might be some discrepancies.

Set this to false in order to have the html input element visible at all times. Drawback: You cannot have overlays over the input field.

placeholder : string

The placeholder text applied to the html input element or the substituted pixi-Text.

placeholderColor : int

The color of the placeholder (has no effect when substituteText is set to false; Use CSS to set the placeholder color).

text : string

The text (value) of the html input element.

maxLength : int

The maximum length of the text.

restrict : RegExp | string

Restricts the text input to a specified character set. Either pass a string containing all possible characters or a regular expression, which will be matched against the whole input string.

htmlInput : HTMLInputElement

Direct access to the native HTML input. Who knows what you're planning to do.

disabled : boolean

Set to true to disable the input.

Methods

focus() : void

Focus the input.

select() : void

Focus the input and have the text in selection.

blur() : void

Remove the focus of the input.

setInputStyle( key : string, value : string ) : void

Change a css style attribute of the input element. For example, to change the font size, use:
input.setInputStyle('fontSize', '21px')

Events

All events are dispatched via the default pixi EventEmitter.

input.on('keydown', keycode => {
    console.log('key pressed:', keycode)
})

keydown -> keycode : int

Dispatched when a key is pressed along with its keycode.

keyup -> keycode : int

Dispatched when a key is released along with its keycode.

input -> text : string

Dispatched when the input's text has been changed along with the current text of the input.

focus

Dispatched when the input has been focused.

blur

Dispatched when the focus to the input has been lost.

Contribute

Feel free to add features or suggest improvements.

pixi-text-input's People

Contributors

hmpthz avatar jeanbenitez avatar mwni avatar yordan-kanchelov 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

pixi-text-input's Issues

Wheel Events

TextInput appears to be 'eating' mouse wheel events. Unfocussed text does not scroll (using pixi-wheel.js to scroll a container holding the input object). Wheel works when input is focussed, but no wheel events reach the container. When unfocussed, no wheel events reach the container and text does not scroll.

Restrict and backspace

With TextInput I can:

  • backspace any character
  • select all with cmd-a (ctrl-A on windows) and then hitting backspace erases everything entered

Then I set restrict to '[a-zA-Z0-9\ ]+'. This causes:

  • backspace works but for the first entered character. I cannot remove that one with backspace. I just have to select everything and start typing
  • select all and then hitting backspace doesn't do anything. Select all and then typing does work though but is less intuitive.

I tried adding \b to the regexp but this doesn't solve the issue. Something prevents backspace to work properly when using the restrict option.

Vertical Alignment

Hi @Mwni, thanks for the effort on this library, really useful :)

Do you plan to support vertical alignment?

Error on adding input textfield to stage

I've been trying to get the text input to work in my project.

"pixi-text-input": "^1.0.6"
"pixi.js-legacy": "5.3.8"

I had to tweak the import as per the first issue thread:
import TextInput from "pixi-text-input"

and when creating the text input field with:
let t1 = new TextInput({...
that seemed to be fine.

However, when I add it to the stage, I get this error:
Uncaught TypeError: (intermediate value).render is not a function
at TextInput.render (pixi-input-test.js:70784:11)
at Container.render (pixi-input-test.js:17434:34)
at Renderer.render (pixi-input-test.js:11239:23)
at Application.render (pixi-input-test.js:45510:23)
at TickerListener.emit (pixi-input-test.js:21105:25)
at Ticker.update (pixi-input-test.js:21560:37)
at Ticker._tick (pixi-input-test.js:21310:23)

Any ideas how to resolve?

PIXI v7 Support

Hi. I download and modify this code for my project =)

Modify functions:

_createSurrogate()

this._surrogate_hitbox.eventMode = 'static';
if (PIXI.VERSION[0] != '7') this._surrogate_hitbox.interactive = true;

_updateSurrogateHitbox(bounds)

this._surrogate_hitbox.eventMode = this._disabled?'auto':'static';
 if (PIXI.VERSION[0] != '7') this._surrogate_hitbox.interactive = !this._disabled;

_createSurrogate()

this._surrogate_hitbox.eventMode = 'static';
if (PIXI.VERSION[0] != '7') this._surrogate_hitbox.interactive = true;

/*some code....*/        

this.addChild(this._surrogate_mask, this._surrogate, this._surrogate_hitbox);

Focus Color

When text field get's focus, the text turns black. Inconvenient if the unfocussed text is white on a black background- everything disappears.

Multiline

Hello.

Is option to make multiline input form?

Dragging causes a framerate dip

Just flagging this as an issue for anyone else that runs across it!

The framerate will take a massive nosedive if you have dozens of text inputs on screen and you're dragging them inside a container; this is because of the bounds calculation that happens in the _update. There's probably a more efficient way to make this happen, though I don't have any suggestions at this time.

Support for Typescript is missing

Sadly your plugin for PIXI.js has no typescript support at all. Unlike PIXI.js, I am not able to include it into my ts project and get it working...
It would be great if some kind of support could be added

Pixi 6

Needs to support current major Pixi version i.e v6

Does not respond to viewport zooming and panning

I'm trying to use this in an application with viewport attached for canvas pan/zoom functionality.
How do I get this text field to respond to viewport zooming and panning?

// create viewport
        const viewport = new Viewport({
            screenWidth: window.innerWidth,
            screenHeight: window.innerHeight,
            worldWidth: 1000,
            worldHeight: 1000,

            interaction: this.app.renderer.plugins.interaction // the interaction module is important for wheel to work properly when renderer.view is placed or scaled
        })

        // add the viewport to the stage
        this.app.stage.addChild(viewport)

        // activate plugins
        viewport
            .drag()
            .pinch()
            .wheel()
            .decelerate()


        // ensure scrolling over canvas element does not scroll page
        this.app.view.addEventListener("wheel", function(evt){
            evt.preventDefault();
        })

        // add a red box
        const sprite = viewport.addChild(new PIXI.Sprite(PIXI.Texture.WHITE))
        sprite.tint = 0xff0000
        sprite.width = sprite.height = 100
        sprite.position.set(0, 0)


        // add input
        // @ts-ignore
        const input = new TextInput({
            input: {
                fontSize: '36px',
                padding: '12px',
                width: '500px',
                color: '#26272E'
            },
            box: {
                default: {fill: 0xE8E9F3, rounded: 12, stroke: {color: 0xCBCEE0, width: 3}},
                focused: {fill: 0xE1E3EE, rounded: 12, stroke: {color: 0xABAFC6, width: 3}},
                disabled: {fill: 0xDBDBDB, rounded: 12}
            }
        })

        input.placeholder = 'Enter your Text...'
        input.x = 500
        input.y = 300
        input.pivot.x = input.width/2
        input.pivot.y = input.height/2
        this.app.stage.addChild(input)

Ability to set custom attributes

I'd like to set following attributes so all spellcheck etc. features are disabled for input:

        autocorrect: 'off',
        autocomplete: 'off',
        autocapitalize: 'off',
        spellcheck: false

Unfortunately these cannot be set as styles but attributes of input. Is it possible? Could you please add this feature?

Bug on iOS, need to click twice on the input to open the keyboard

What happen :
On iOS Chrome / Safari 13.5 on the first click it take the focus but the it didn't open the keyboard

Behavior expected :
We click it take the focus and open the keyboard

What we try :
use focus() one or more time on touch
use select() one or more time on touch

Note :
The bug is easily reproducible on the demo link
It works as expected on Android.

Thanks in advance.

Placeholder is not removed

When I'm writing the username the placeholder is not removed. See the screenshot below
image

Code:

const username_input = new PIXI.TextInput({
        input: {
            fontSize: '38px',
            padding: '14px',
            width: '400px',
            color: '#26272E'
        }, 
        box: {
            default: {fill: 0xFFFFFF, rounded: 12, stroke: {color: 0xC8C8C8, width: 3}}
        }
    });
username_input.x = app.screen.width/2-200;
username_input.y = app.screen.height/2;

username_input.placeholder = 'Username'

app.stage.addChild(username_input);

dead demo links

Please host your demos on github or some other reliable provider (codepen?)

The current ones are 404ing :)

Text align center not supported

Text alignment doesn't work in the Pixi.Text surrogate, probably because HTML Input style is "textAlign" and for Pixi.Text just "align". I can set textAlign in the input options and it works, but if I have substituteText set true, the surrogate just goes to the left when the text input is unfocused.

It would probably be easy to fix by adding an exception for it to the _deriveSurrogateStyle?

Input Width

Is it possible to change the width after an input has been created? I've tried several approaches but not sure if it's possible.

Does not handle type 'password'

_deriveSurrogateText on line 423 needs to be updated to handle password type. The following is the code I used to handle it for my project:
_proto._deriveSurrogateText = function _deriveSurrogateText() {
var txt = this._dom_input.value;
if(this._dom_input.value.length === 0)
{
txt = this._placeholder;
}else if(this._dom_input.type == 'password'){
txt = "•".repeat(this._dom_input.value.length);
}
return txt;
};

Bug : inconsistent behavior when using paddingTop

when using some combinaison the focus position of the text is different than the blur position

for example with

			input: {
				lineHeight: '40px',
				fontSize: '14px',
				padding: '16px',
				paddingTop: '18px',
				paddingLeft: '14px',
				paddingBottom: '8px',
				width: '200px',
				color: '#5b1289',
			},

Typings missing

Where I can find typings for this to use with typescript?

Set input type

Hi!
I try to use Your module for login form in my game, I noticed that there is no way to set different input types, for example "password".
Having looked at the code, I decided that adding it would not be difficult.
For example update method:
_createDOMInput(type){
if(this._multiline){
this._dom_input = document.createElement('textarea')
this._dom_input.style.resize = 'none'
}else{
this._dom_input = document.createElement('input')

  this._dom_input.type = type
}

and set type as constructor parameter
styles, type

Max length

Hello.

Please add max length param.

Thank you for your work.

Duplicate identifier 'substituteText' in ts

I have installed package using npm install. As a result I have errors. As you see in screenshot some properties are marked red in pixi-textinput-v5.

And the error message says "Duplicate identifier 'substituteText'.ts(2300)". The same is for placeholder, disabled, maxLength, restrict.

image

remove direct dependency of pixi.js

the latest published package.json:

{
  "name": "pixi-text-input",
  "version": "1.0.4",
  "description": "Plugin for pixi.js which provides a convenient way of adding a text input to the pixijs-stage.",
  "main": "PIXI.TextInput.js",
  "dependencies": {
    "pixi.js": "^4.8.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Mwni/PIXI.TextInput.git"
  },
  "keywords": [
    "pixi",
    "pixi.js",
    "input",
    "text",
    "ui"
  ],
  "author": "Mwni",
  "license": "MIT"
}

pixi.js should be a peerDependency (and changed to include v5 support). as-is, this package installs its own v4 pixi.js, and doesn't work when used from v5 pixi.js.

Request: Please add a way to detect mousedown and mouseup events

Hello,

Thank you for the TextInput ! :)

How can I make this work:

                const input = new TextInput(input_style,box_styles);
                input.placeholder = 'Search feature';
                input.x = this.object.position.x;
                input.y = this.object.position.y + index * viewport.gridSize * 2;
                input.height = viewport.gridSize * 2;
                input.width = this.object.width;
                viewport.addChild(input);
                input.on('mousedown', (e) => {
                    console.log('mousedown in text');
                    e.stopPropagation();
                });
                input.on('mouseup', (e) => {
                    console.log('mouseup in text');
                    e.stopPropagation();
                });

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.