treeJSbezierTriangle

by Lamik

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/101/three.min.js"></script>
<canvas></canvas>

CSS

body {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: #1c2228;
  overflow: hidden;
}

JavaScript

///////////////////////////////////////////////////////
// THIS PART/CLASS IS FOR ALGORITHMS AND CALCULATIONS
///////////////////////////////////////////////////////
class Geometry {

  constructor() { this.init(); } 

  init(n) {
    this.pts = [
      { x:-16, y: -8, z:0,  color:0xcc0000 }, // p003 RED
      { x:8,   y:-12, z:0,  color:0x888888 }, // p201
      { x:-8,  y:-12, z:0,  color:0x999999 }, // p102    
      { x:16,  y:-8,  z:0,  color:0x00cc00 }, // p300 GREEN
      { x:12,  y:-6,  z:-8, color:0x777777 }, // p210
      { x:8,   y:6,   z:-8, color:0x666666 }, // p120
      { x:0,   y:12,  z:0,  color:0x0000cc }, // p030 BLUE
      { x:-8,  y:6,   z:-8, color:0x555555 }, // p021
      { x:-12, y:-6,  z:-8, color:0x444444 }, // p012
      { x:0,   y:0,   z:8,  color:0xffff00 }, // p111 YELLOW (plane control point)
    ];
    
    this.mainTriangle = [this.pts[0],this.pts[3],this.pts[6]];
    
    this.bezierCurvesPoints = [
    	[ this.pts[0], this.pts[2], this.pts[1], this.pts[3] ],
        [ this.pts[3], this.pts[4], this.pts[5], this.pts[6] ],
        [ this.pts[6], this.pts[7], this.pts[8], this.pts[0] ]
    ];
    
    //this.triangles = [
    // { points: [this.pts[0], this.pts[1], this.pts[2]], color: null }, // wireframe
    // { points: [this.pts[1], this.pts[2], this.pts[3]], color: 0xffff00 } // yellow
    //]
    
    this.triangles = this.genTrianglesForCubicBezierTriangle(25, this.pts);
  }
  
  // n = number of triangles per triangle side
  genTrianglesForCubicBezierTriangle(n, controlPoints) {
    let bar= this.barycentricCoords(n);     // domain in barycentric coordinats   
    let ti = this.genTrianglesIndexes(n);   // indexes of triangles (in bar array)
        
    let val= bar.map(x => this.calcCubicBezierTriangleValue(controlPoints,...x));  // Calc Bezier triangle vertex for each domain (bar) point    
    let tv= ti.map(tr=> tr.map(x=>val[x]) );         // generate triangles using their indexes (ti) and val    
    return...