Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

p5.jsのbeginContour(), endContour()を使う

/*
 * contours objects
 *
 * @author aadebdeb
 * @date 2017/02/05
 */

var objs = [];
var type = 0;
var bgColor, fillColor;

function setup() {
  createCanvas(windowWidth, windowHeight);
  for(var i = 0; i < 100; i++) {
    objs.push(new Obj(i));
  }
  bgColor = [color(40), color(220)];
  fillColor = [[color(0, 30, 30), color(140, 220, 220)], [color(220, 220, 140), color(30, 30, 0)]];
}

function draw() {
  background(bgColor[type]);
  for(var i = 0; i < objs.length; i++) {
    objs[i].render();
  }
}

function mousePressed() {
  if(type == 0) {
    type = 1;
  } else {
    type = 0;
  }
}

function Obj(index) {
  
  this.x = random(width);
  this.y = random(height);
  if (random(1) < 0.5) {
    this.vx = random(1, 5) * (random(1) < 0.5 ? 1: -1);
    this.vy = 0;
  } else {
    this.vx = 0;
    this.vy = random(1, 5) * (random(1) < 0.5 ? 1: -1);
  }
  this.outerSize = map(index, 0, 100, 70, 10);
  this.innerSize = this.outerSize / 2;
  this.index = index;

  this.render = function() {
    stroke(bgColor[type]);
    strokeWeight(1);
    fill(lerpColor(fillColor[type][0], fillColor[type][1], this.index / 100));
    push();
    translate(this.x, this.y);
    beginShape();
    vertex(-this.outerSize, -this.outerSize);
    vertex(this.outerSize, -this.outerSize);
    vertex(this.outerSize, this.outerSize);
    vertex(-this.outerSize, this.outerSize);
    beginContour();
    vertex(-this.innerSize, -this.innerSize);
    vertex(-this.innerSize, this.innerSize);
    vertex(this.innerSize, this.innerSize);
    vertex(this.innerSize, -this.innerSize);
    endContour();
    endShape(CLOSE);
    pop();
    this.x += this.vx;
    if (this.x < -this.outerSize) {
      this.x = width + this.outerSize;
    } else if(this.x > width + this.outerSize) {
      this.x = -this.outerSize;
    }
    this.y += this.vy;
    if (this.y < -this.outerSize) {
      this.y = height + this.outerSize;
    } else if(this.y > height + this.outerSize) {
      this.y = -this.outerSize;
    }
  }
  
}
f:id:aa_debdeb:20170202085506j:plain