3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

p5.jsで矩形をドラッグする

Last updated at Posted at 2017-04-06

p5.jsとは

Processingっぽい事ができるJavaScriptライブラリです。Web上でグラフィカルな表現をしたい時に使えます。
公式のリファレンス読めばとりあえず動かせます。
公式サイト

キャンバスに描画したオブジェクトをドラッグで動かす

サンプルはこちら(Runstantに飛びます)

ざっくり解説

p5.jsに搭載されているmousePressed、mouseDragged、mouseReleased関数をそれっぽく組み合わせて実現します。

マウスクリックした瞬間に呼ばれるイベント(mousePressed)

function mousePressed(){
  for(var i=objList.length-1;i>=0;i--){
    if(objList[i].pressed()){
      break;
    }
  }
}

画面に描画するオブジェクトに対してクリック判定の処理を呼び出します。
クリックされたオブジェクトが1つ見つかった時点で終了します。
オブジェクトごとのクリック判定処理の順番は、オブジェクトを描画する順番とは逆にしておきます。
(より前面に描画されたオブジェクトを優先的にドラッグできるようにするため)

オブジェクトのpressed関数の中身はこんな感じです。
マウスの位置が矩形の範囲内にあるかどうかを判定してます。
ドラッグを開始する際はオブジェクトのクリック座標を保存しておきます。

DragObject.prototype.pressed = function(){
  
  if(this.x <= mouseX && mouseX <= this.x + this.wid &&
    this.y <= mouseY && mouseY <= this.y + this.hei){
      this.pressedX = this.x - mouseX;
      this.pressedY = this.y - mouseY;
      this.draggedFlg = true;
  }
  return this.draggedFlg;
}

マウスドラッグ中に呼ばれるイベント(mouseDragged)

function mouseDragged() {
  for(var obj of objList){
    obj.drag();
  }
}

オブジェクトのドラッグイベントを呼び出します。
オブジェクトの位置を更新してます。

DragObject.prototype.drag = function(){
  if(this.draggedFlg){
    this.x = mouseX + this.pressedX;
    this.y = mouseY + this.pressedY;
  }
}

ドラッグ終了時のイベント(mouseReleased)

function mouseReleased(){
  for(var obj of objList){
    obj.release();
  }
}

オブジェクトのドラッグ終了イベントを呼び出します。

DragObject.prototype.release = function(){
  this.draggedFlg = false;
}

もっと良い書き方たくさんありそうですが、とりあえず動いたので現場からは以上です。

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?