LoginSignup
9
8

More than 5 years have passed since last update.

p5.jsで何か作るときにbackground()の挙動でハマっていた

Last updated at Posted at 2015-06-16

たまに触るけど、全然慣れないp5.js http://p5js.org/

こんな感じのものを作りました。

  • クリックしていると両サイドの線が集まってきて、真ん中にくると画面の色が変わります。
  • クリックしていない状態だと線が外に逃げます。

setup()とdraw()とbackground()

それで、何が問題かというと。

setup()とdraw()とbackground()の挙動について理解していませんでした。

p5ではbackgroung()で背景色を指定してあげます。

例えば、

app.js
function setup() {
  createCanvas(800, 400);
  background(0);//背景黒
}

こんな感じにすると背景黒のキャンバスが表示されます。
まずは問題無いです。

その黒い画面にこんな感じで図形を動かす場合、どうするか

background()が分かってなかった例

この流れで、作るとこんな感じになりそうですね。

app.js
var x,y;

function setup() {
  createCanvas(800, 400);
  stroke(255); //線を白く
  background(0);//背景黒
  y = height * 0.5; //画面中央
  x = 0;
}

function draw(){
    x++;
    rect(x, y, 10, 1);
}

これを実行するとこうなります。

(これはこれで、こういう挙動をさせたい場合にはいいかもしれませんが)意図する挙動と違いました。

雰囲気で予想はつきますが、フレームの更新がされずにフレーム毎に上書きしているっぽいですね。前のフレームで描画した内容のクリアはどこでやるんだ...というところですね。

ドキュメントによるとクリアがbackground()の中で行われてるみたい

これはメソッド名が分かりにくいなぁと感じました汗
ドキュメントちゃんと読んで無かった自分が悪いんだけど汗

Description
The background() function sets the color used for the background of the p5.js canvas. The default background is light gray. This function is typically used within draw() to clear the display window at the beginning of each frame, but it can be used inside setup() to set the background on the first frame of animation or if the background need only be set once.

なるほどですね。
書き換えが発生し無い場合は最初のsetup()で一回だけ呼ぶやり方でいいけど、
基本的にはbackground()はdraw()の中で呼び出しましょうとのこと。

ということでこうなります。

app.js
var x,y;

function setup() {
  createCanvas(800, 400);
  stroke(255); //線を白く
  y = height * 0.5; //画面中央
  x = 0;
}

function draw(){
  background(0);//背景黒
  x++;
  rect(x, y, 10, 1);
}

ひとまず完成

という感じで挙動に無駄になやんだ感じでしたがひとまづの完成。

app.js
var CW = 1000,
    CH = 400;
var sceneFlag = 0,
    clickFlag = 0;
var bgColor = 0,
    stColor = 255;
var y,x1,x2;
var speed = 3;

function setup() {
  createCanvas(CW, CH);// Create object
  y = height * 0.5; //画面中央に
  x1 = 0;
  x2 = width;
}

function draw() {
  background(bgColor);//背景を黒に
  stroke(stColor); //線を消す

  if(clickFlag === 0){
    //クリックしていない場合
    if(x1 > 0) x1 = x1 - speed;
    if(x2 <= width) x2 = x2 + speed;
  }else{
    //クリック長押し中
    x1 = x1 + speed;
    x2 = x2 - speed;
    if(sceneFlag === 0 && x2 <= CW/2){
      sceneFlag = 1; //一度切り
      bgColor = color('magenta');
      stColor = bgColor;
    }
  }
  rect(0, y, x1, 1);
  rect(x2, y, width, 1);
}

//クリック長押し処理
var loop;
var pressLoop = function(){
  clickFlag = 1; //クリック中
};

function mousePressed() {
  loop = setInterval(pressLoop,16);
}

function mouseReleased(){
  clearInterval(loop);
  clickFlag = 0; //クリックしていない
}
9
8
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
9
8