三角形の3Dマッピングの勉強でメモ

{
  class Matrix {

    constructor (a = 1, b = 0, c = 0, d = 1) {
      this.matrix = [a, b, c, d];
    }

    getInverse () {//逆数
      let
        [a, b, c, d] = this.matrix,
        z = a * d - b * c;
      return z ? new Matrix (d / z, -b / z, -c / z, a /z): null;
    }
    
    multiplication (arg) {//乗算
      let
        [A, B, C, D] = this.matrix,
        [a, b, c, d] = arg.matrix;

      this.matrix = [
        A * a + B * c,
        A * b + B * d,
        C * a + D * c,
        C * b + D * d
      ];
      return this;
    }
  }
  //this.Matrix = Matrix;


  const
    drawTriangle = (ctx, img, trPoint, uvPoint) => {
      let
        {width, height} = img,
        [[ux, uy], [u1x, u1y], [u2x, u2y]] = uvPoint,
        m0 = new Matrix (
          (u1x - ux) * width, (u1y - uy) * height,
          (u2x - ux) * width, (u2y - uy) * height
        ).getInverse ();

      if (m0) {
        let
          [[vx, vy], [v1x, v1y], [v2x, v2y]] = trPoint,
          uw = ux * width,
          uh = uy * height,
          m1 = new Matrix (v1x - vx, v1y - vy, v2x - vx, v2y - vy),
          [a, b, c, d] = m0.multiplication (m1).matrix,
          e = vx - (a * uw + c * uh),
          f = vy - (b * uw + d * uh);

        ctx.save ();
        	ctx.beginPath ();
        	ctx.moveTo (vx, vy);
        	ctx.lineTo (v1x, v1y);
        	ctx.lineTo (v2x, v2y);
        	ctx.clip ();

        	ctx.transform (a, b, c, d, e, f)
        	ctx.drawImage (img, 0, 0);
	      ctx.restore ();
	    }
    };
  
   
  this.drawTriangle = drawTriangle;
}

その2
空間上にある中心点Aから離れた球体面の点Bを元に、マッピングしたい画像上の位置に変換する(書きかけ)

function getMappingPoisition (center, target) {
  let
    pi = Math.PI / 2,
    pi2 = pi + pi,
    atan = Math.atan,
    x = target.x - center.x,
    y = target.y - center.y,
    z = target.z - center.z;
  
  let a = atan (z / x);
  if (x < 0)
    a += pi;
  else if (z < 0)
    a += pi2;
  
  let b = atan (y / x);
  if (x < 0)
    b += pi;
  else if (y < 0)
    b += pi2;
  
  return {x: a / pi2, y: b / pi };
}