Pixi.jsでオブジェクトのドラッグ&ドロップを実装する事ができます。
実際のところ
画像を読みだす部分からイベント実装までを抽出すると、こんな感じです。
PIXI.loader .add("catImg","views/images/cat.png") .load(setup); function setup() { //Create the `cat` sprite from the texture var cat = new PIXI.Sprite( PIXI.loader.resources.catImg.texture ) // インタラクティブ性を持たせる。 // マウスやタッチイベントで操作できるように cat.interactive = true // マウスオーバーしたら、アイコンを矢印から手に cat.buttonMode = true // アンカーポイントの位置。中心なら0.5 cat.anchor.set(0.5) //拡大率 cat.scale.set(1) // イベントを設定 cat // ドラッグを開始 .on('mousedown', onDragStart) .on('touchstart', onDragStart) // ドロップ(ドラッグを終了) .on('mouseup', onDragEnd) .on('mouseupoutside', onDragEnd) .on('touchend', onDragEnd) .on('touchendoutside', onDragEnd) // ドラッグ中 .on('mousemove', onDragMove) .on('touchmove', onDragMove) // レンダリングの絶対位置 cat.position.x = 100 cat.position.y = 100 //stageに画像を追加 stage.addChild(cat) //レンダリング renderer.render(stage) }
アニメーションをさせるには、明示的に宣言しないと駄目です。
// アニメーションまわり // これがないと、ドラッグ&ドロップもできない requestAnimationFrame( animate ) function animate() { requestAnimationFrame(animate) renderer.render(stage) }
あとは、クリック時イベントです。
そのまんまだと面白くないので、x軸が200以上の所に落とすとalertを出すようにしました。
function onDragStart(event) { // store a reference to the data // the reason for this is because of multitouch // we want to track the movement of this particular touch this.data = event.data this.alpha = 0.5 this.dragging = true } function onDragEnd() { this.alpha = 1 this.dragging = false // set the interaction data to null this.data = null // 移動検知実験 if (this.position.x > 200) { alert("MOVED!") } } function onDragMove() { if (this.dragging) { var newPosition = this.data.getLocalPosition(this.parent) this.position.x = newPosition.x this.position.y = newPosition.y } }