Skip to content

Instantly share code, notes, and snippets.

@gbuszmicz
Last active April 16, 2019 23:33
Show Gist options
  • Save gbuszmicz/8febce07a7dfa723310ce3b820f1a3f1 to your computer and use it in GitHub Desktop.
Save gbuszmicz/8febce07a7dfa723310ce3b820f1a3f1 to your computer and use it in GitHub Desktop.
Pixi slider component for React
import { CustomPIXIComponent } from 'react-pixi-fiber'
import * as PIXI from 'pixi.js'
const TYPE = 'Button'
export const behavior = {
customDisplayObject: props => new PIXI.Graphics(),
customApplyProps: (instance, oldProps, newProps) => {
const {
fill,
width,
height,
scale,
onChange,
currentPosition,
stepWidth,
moveToX,
btnWidth,
} = newProps
const onDragStart = event => {
instance.data = event.data
instance.dragging = true
}
const onDragEnd = event => {
delete instance.data
instance.dragging = false
}
const onDragMove = event => {
const min = 0
// parent._width is the width of the background, and width is the width of this button
const max = instance.parent._width - width
if (instance.dragging) {
const newPosition = instance.data.getLocalPosition(instance.parent)
instance.x = newPosition.x
if (instance.x > max) instance.x = max
if (instance.x < min) instance.x = min
onChange({ x: instance.x })
}
}
instance.clear()
instance.beginFill(fill)
instance.drawRect(0, 0, width, height)
instance.endFill()
instance.interactive = true
instance.buttonMode = true
instance.on('pointerdown', onDragStart)
instance.on('pointerup', onDragEnd)
instance.on('pointerupoutside', onDragEnd)
instance.on('pointermove', onDragMove)
if (oldProps.moveToX && oldProps.moveToX !== moveToX) {
instance.x = 0
instance.x = moveToX
// Callback
onChange({ x: instance.x })
}
if (!oldProps.currentPosition) {
// Only when mounting the component
instance.x = currentPosition * stepWidth
}
if (oldProps.scale && oldProps.scale !== scale) {
instance.x = 0
instance.x = currentPosition * stepWidth
}
},
}
export default CustomPIXIComponent(behavior, TYPE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment