iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 29
2
自我挑戰組

學JS的心路歷程系列 第 29

學JS的心路歷程 Day29 - PixiJS - 基礎(三)

  • 分享至 

  • twitterImage
  •  

今天我們來試著移動圖片吧!

首先,一樣先把圖片放到 PIXI 的 stage 中:

let app = new PIXI.Application({
  width: 800,
  height: 600,
  backgroundColor: 0x1099bb
});
let imageURL = "./image/bunny.png";

PIXI.loader
    .add('bunny',imageURL)
    .load(init);

function init(loader,resources) {
    let bunny = new PIXI.Sprite(
        resources['bunny'].texture 
    );
    app.stage.addChild(bunny);
}

但是,一直顯示在左上角實在是有點麻煩,我們可以這樣寫:

function init(loader,resources) {
    let bunny = new PIXI.Sprite(
        resources['bunny'].texture
    );
    bunny.x = app.screen.width / 2;
    bunny.y = app.screen.height / 2;
    bunny.scale.set(3.5, 3.5);
    
    app.stage.addChild(bunny);
}

bunnyx,y 設為 canvas 的一半,並用 scale 把大小設為 3.5 倍。

接著我們監聽滑鼠事件:

function init(loader,resources) {
    let bunny = new PIXI.Sprite(
        resources['bunny'].texture 
    );
    bunny.x = app.screen.width / 2;
    bunny.y = app.screen.height / 2;
    bunny.scale.set(3.5, 3.5);
    bunny.anchor.set(0.5);
    mouseEvent(bunny);
    app.stage.addChild(bunny);
}
function mouseEvent(bunny){
  bunny.interactive = true;
  bunny.buttonMode = true;
  bunny.on('mousedown', onDragStart)
       .on('mouseup', onDragEnd)
}

記得要把監聽的物件的 interactive 設為 true,否則會無法觸發!

buttonMode 是讓滑鼠靠近圖片時會轉為手指圖案(截圖弄不出來只能用說明的)。

然後,撰寫監聽事件,讓圖片按下時會透明。

function onDragStart(event) {
  this.alpha = 0.5;
}
function onDragEnd() {
  this.alpha = 1;
}

接著我們需要能按下拖移:

bunny.on('mousedown', onDragStart)
    .on('mouseup', onDragEnd)
    .on('mousemove', onDragMove);
    
function onDragStart(event) {
  this.alpha = 0.5;
  this.dragging = true;
}

function onDragEnd() {
  this.alpha = 1;
  this.dragging = false;
}

function onDragMove(event) {
  if (this.dragging) {
    let newPosition = event.data.getLocalPosition(this.parent);
    this.x = newPosition.x;
    this.y = newPosition.y;
  }
}

首先,我們先對 bunny 新增一個 dragging 屬性,判斷滑鼠按下及放開的狀態;

接著再設定移動時,如果 draggingtrue ,利用getLocalPosition 取得 bunny.parent 的座標位置,並同時更新 bunny 的座標位置。

就可以順利移動了喔!

那麼 PixiJS 就先到這邊告一段落了,一樣如果有錯誤及來源未附上歡迎留言指正,我們明天見!

參考資料:
PixiJS Doc
PixiJS example


上一篇
學JS的心路歷程 Day28 - PixiJS - 基礎(二)
下一篇
學JS的心路歷程 Day30 - JS 應用 - 搶優惠券
系列文
學JS的心路歷程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
thevid
iT邦新手 5 級 ‧ 2018-11-13 18:22:46

wow 這樣就可以做棋盤 紙娃娃 圖片上貼貼紙了

我要留言

立即登入留言