The principle of image stretching is essentially rotation of vertex coordinates. Color to grayscale is essentially changing the color of the texture.
1. Picture stretching
1. Vertex shader code
By rotating the vertex coordinates around the x and y axes, the image can be stretched.
<script type="shader-source" id="vertexShader"> / Float set to medium precision mediump float; attribute vec2 a_Position; varying vec2 v_Uv; attribute vec2 a_Uv; uniform mat4 mx; uniform mat4 my;void main(){
gl_Position = mx*my*vec4(a_Position, 0.1);
// Texture coordinate difference calculation
v_Uv = a_Uv;
}
</script>
Copy the code
2. JavaScript code
- Apply colours to a drawing
WebGL
Add the code to the Render function to rotate the vertex coordinates.
function render(gl, count) {
// Set the clear color to black.
gl.clearColor(0.0.0.1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, count);
}
function tranlate() {
const angle = 30.0;
const rad = angle * Math.PI / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
const mx = gl.getUniformLocation(program, 'mx');
const mxArr = new Float32Array([
1.0.0.0.0, cos, -sin, 0.0, sin, cos, 0.0.0.0.1
])
gl.uniformMatrix4fv(mx, false, mxArr);
const my = gl.getUniformLocation(program, 'my');
const myArr = new Float32Array([
cos, 0, -sin, 0.0.1.0.0, sin, 0, cos, 0.0.0.0.1
])
gl.uniformMatrix4fv(my, false, myArr);
}
Copy the code
The stretching effect of the picture is as follows:
2, color map to gray map
Grayscale images only have black and white colors. You’re essentially modifying the brightness of the light. Black equals no light and white equals maximum light intensity. By calculating the VALUE of RGB components, gl_FragColor is finally given to achieve the grayscale effect. The brightness calculation formula is as follows:
// The RGB coefficients add up to 1 to ensure that the calculated result does not exceed the default WebGL color component maximum of 1.
//Brightness =0.199 x R + 0.187 x G + 0.714 x B
Copy the code
To turn a color image into a grayscale image, you only need to modify the code of the slice shader.
- Chip shader code
<script type="shader-source" id="fragmentShader">
// Float is set to medium precision
precision mediump float;
uniform sampler2D u_Texture;
varying vec2 v_Uv;
void main(){
//gl_FragColor=texture2D(u_Texture, v_Uv);
vec4 texture=texture2D(u_Texture, v_Uv);
// Color map to gray map formula
// Calculate the sum of the three components of RGB light energy, i.e., brightness
float luminance = 0.199*texture.r+0.187*texture.g+0.714*texture.b;
// Pixel by pixel assignment, RGB is the same brightness value, use black and white to express the change of light and shade of the picture
gl_FragColor = vec4(luminance,luminance,luminance,1.0);
}
</script>
<script>
Copy the code
The final effect is as follows:
reference
Introduction to WebGL and Practice WebGL official document