(一)需求
被问到矩阵23和矩阵32相乘是几乘几。我懵了。记录总结下
(二)矩阵想成
1、为什么矩阵相乘对前端很重要?
可以用少量的数字描述大量的空间中的变换,并且能轻易地在程序间共享。矩阵可以不同的坐标空间,甚至一些矩阵乘法可以将一组数据从一个坐标空间映射到另一个坐标空间。矩阵能够高效率地保存生成它们的每一步变换。
- CSS3 3D变换时,是用的矩阵相乘;
- WebGL使用中大量使用了矩阵运算,各种各样的运算,如点定位、光线运算、动态角色
显卡尤其擅长大量的点乘矩阵运算
2、矩阵相乘的定义
比如,
let arr1=[[2,3,-1],[6,1,-2]]
let arr2=[[4,-5],[-3,0],[1,2]]
webGL 中的应用
function WebGLBox() {
// Setup the canvas and WebGL context
this.canvas = document.getElementById('canvas');
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.gl = MDN.createContext(canvas);
var gl = this.gl;
// Setup a WebGL program, anything part of the MDN object is defined outside of this article
this.webglProgram = MDN.createWebGLProgramFromIds(gl, 'vertex-shader', 'fragment-shader');
gl.useProgram(this.webglProgram);
// Save the attribute and uniform locations
this.positionLocation = gl.getAttribLocation(this.webglProgram, 'position');
this.colorLocation = gl.getUniformLocation(this.webglProgram, 'color');
// Tell WebGL to test the depth when drawing, so if a square is behind
// another square it won't be drawn
gl.enable(gl.DEPTH_TEST);
}
WebGLBox.prototype.draw = function(settings) {
// Create some attribute data; these are the triangles that will end being
// drawn to the screen. There are two that form a square.
var data = new Float32Array([
//Triangle 1
settings.left, settings.bottom, settings.depth,
settings.right, settings.bottom, settings.depth,
settings.left, settings.top, settings.depth,
//Triangle 2
settings.left, settings.top, settings.depth,
settings.right, settings.bottom, settings.depth,
settings.right, settings.top, settings.depth
]);
// Use WebGL to draw this onto the screen.
// Performance Note: Creating a new array buffer for every draw call is slow.
// This function is for illustration purposes only.
var gl = this.gl;
// Create a buffer and bind the data
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
// Setup the pointer to our attribute data (the triangles)
gl.enableVertexAttribArray(this.positionLocation);
gl.vertexAttribPointer(this.positionLocation, 3, gl.FLOAT, false, 0, 0);
// Setup the color uniform that will be shared across all triangles
gl.uniform4fv(this.colorLocation, settings.color);
// Draw the triangles to the screen
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
````
### 3、JS 如何进行矩阵相乘
#### (1)使用JS 数组来表示数据
+ 使用for循环来遍历矩阵相乘;
#### (2)使用现成的封装函数
比如,CSS3 matrix()
transform: matrix(1.2, 0.2, -1, 0.9, 0, 20);
#### (3)使用封装好的函数库
gl-matrix
https://github.com/toji/gl-matrix
### 参考链接
MDN
https://developer.mozilla.org/zh-CN/docs/Web/API/WebGL_API/Matrix_math_for_the_web
### 写在最后的话
##### 1、我建了一个前端学习小组
感兴趣的伙伴,可以加我微信:learningisconnecting
##### 2、学习路上,常常会懈怠
《有想学技术需要监督的同学嘛~》
https://mp.weixin.qq.com/s/FyuddlwRY7DsHUejCjiVug
##### 3、分享成长认知方法
欢迎关注我的公众号:国星聊成长
每周分享我学习到的成长/认知方法