> show canvas only <


/* built with Studio Sketchpad: 
 *   https://sketchpad.cc
 * 
 * observe the evolution of this sketch: 
 *   https://p5js.sketchpad.cc/sp/pad/view/ro.RmWK6w2aY9t/rev.8
 * 
 * authors: 
 *   GoToLoop

 * license (unless otherwise specified): 
 *   creative commons attribution-share alike 3.0 license.
 *   https://creativecommons.org/licenses/by-sa/3.0/ 
 */ 



<script src=http://p5js.org/js/p5.min.js></script>

<script>

/**
 * Random Polygon Shape (v2.03)
 * by Jonasan & GoToLoop (2016-Feb-24)
 *
 * https://forum.Processing.org/two/discussion/15064/
 * how-to-avoid-crossing-borders-in-a-random-polygon
 *
 * http://p5js.SketchPad.cc/sp/pad/view/ro.RmWK6w2aY9t/latest
 */

var poly

function setup() {
  createCanvas(300, 300)
  smooth().frameRate(5).noLoop()
  poly = new Polygon(width>>1, height>>1)
}

function draw() {
  background('#' + hex(~~random(0x1000), 3))
  poly.display()
  document.title = `Corners: ${poly.corners.length}`
}

function keyPressed() {
  poly.rebuildPolygon()
  redraw()
}

function mousePressed() {
  keyPressed()
}

class Polygon {
  constructor (v, y) {
    this.beginCorner = typeof y === 'number'?
                       createVector(v, y) : createVector(v.x, v.y)

    this.s = createGraphics(width, height)
    this.s.fill(this.FILL).stroke(this.STROKE).strokeWeight(1.5)

    this.rebuildPolygon()
  }

  display() {
    image(this.s, 0, 0)
  }

  rebuildPolygon() {
    this.rebuildCorners(), this.rebuildShape()
  }

  rebuildCorners() {
    const qty = ~~random(this.CORNERS_MIN, 1 + this.CORNERS_MAX),
          rad = TAU/qty

    this.corners = Array(qty)

    for (let i = 0; i < qty; ++i) {
      const x = cos(i*rad) * random(this.RAD_MIN, this.RAD_MAX)
      const y = sin(i*rad) * random(this.RAD_MIN, this.RAD_MAX)
      this.corners[i] = createVector(x, y)
    }
  }

  rebuildShape() {
    this.s.clear()
    this.s.translate(this.beginCorner.x, this.beginCorner.y)

    this.s.beginShape()
    for (const v of this.corners)  this.s.vertex(v.x, v.y)
    this.s.endShape(CLOSE)

    this.s.resetMatrix()
  }
}

Polygon.prototype.CORNERS_MIN = 3
Polygon.prototype.CORNERS_MAX = 7
Polygon.prototype.DIM = 6
Polygon.prototype.RAD_MIN = 6*Polygon.prototype.DIM
Polygon.prototype.RAD_MAX = 24*Polygon.prototype.DIM
Polygon.prototype.FILL = 'yellow'
Polygon.prototype.STROKE = 0

Object.freeze(Object.freeze(Polygon).prototype)

</script>