Matrix32.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. const Matrix32 = (() =>
  2. {
  3. // private
  4. let self;
  5. let m = [1, 0, 0, 1, 0, 0];
  6. const reset = () =>
  7. {
  8. const m = [1,0,0,1,0,0];
  9. };
  10. const multiply = mat =>
  11. {
  12. const m0=m[0]*mat[0]+m[2]*mat[1];
  13. const m1=m[1]*mat[0]+m[3]*mat[1];
  14. const m2=m[0]*mat[2]+m[2]*mat[3];
  15. const m3=m[1]*mat[2]+m[3]*mat[3];
  16. const m4=m[0]*mat[4]+m[2]*mat[5]+m[4];
  17. const m5=m[1]*mat[4]+m[3]*mat[5]+m[5];
  18. m=[m0,m1,m2,m3,m4,m5];
  19. };
  20. const screenPoint=(transformedX, transformedY) =>
  21. {
  22. // invert
  23. const d =1/(m[0]*m[3]-m[1]*m[2]);
  24. im = [ m[3]*d, -m[1]*d, -m[2]*d, m[0]*d, d*(m[2]*m[5]-m[3]*m[4]), d*(m[1]*m[4]-m[0]*m[5]) ];
  25. // point
  26. return(
  27. {
  28. x:transformedX*im[0]+transformedY*im[2]+im[4],
  29. y:transformedX*im[1]+transformedY*im[3]+im[5]
  30. });
  31. };
  32. const transformedPoint=(screenX, screenY) => ({
  33. x:screenX*m[0] + screenY*m[2] + m[4],
  34. y:screenX*m[1] + screenY*m[3] + m[5]
  35. });
  36. // public
  37. class Matrix32
  38. {
  39. constructor()
  40. {
  41. self = this;
  42. }
  43. // shared methods
  44. translate(x, y)
  45. {
  46. const mat = [1, 0, 0, 1, x, y];
  47. multiply(mat);
  48. }
  49. rotate(rAngle)
  50. {
  51. const c = Math.cos(rAngle);
  52. const s = Math.sin(rAngle);
  53. const mat = [c, s, -s, c, 0, 0];
  54. multiply(mat);
  55. }
  56. scale(x, y)
  57. {
  58. const mat = [x, 0, 0, y, 0, 0];
  59. multiply(mat);
  60. }
  61. skew(radianX, radianY)
  62. {
  63. const mat=[ 1, Math.tan(radianY), Math.tan(radianX), 1, 0, 0 ];
  64. multiply(mat);
  65. }
  66. reset()
  67. {
  68. reset();
  69. }
  70. setContextTransform(ctx)
  71. {
  72. ctx.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]);
  73. }
  74. resetContextTransform(ctx)
  75. {
  76. ctx.setTransform(1,0,0,1,0,0);
  77. }
  78. getTransformedPoint(screenX, screenY)
  79. {
  80. return transformedPoint(screenX, screenY);
  81. }
  82. getScreenPoint(transformedX, transformedY)
  83. {
  84. return screenPoint(transformedX, transformedY);
  85. }
  86. getMatrix()
  87. {
  88. const clone = [m[0], m[1], m[2], m[3], m[4], m[5]];
  89. return(clone);
  90. }
  91. }
  92. return(Matrix32);
  93. })();