# 如何在着色器中旋转和平移矩形纹理 [英] how to rotate and translate rectangle texture in shader

### 问题描述

``````precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D s_texture;
mat3 makeTranslation(vec2 t) {
mat3 m = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, t.x, t.y, 1.0);
return m;
}
mat3 m = mat3(c, -s, 0, s, c, 0, 0, 0, 1);
return m;
}
mat3 makeScale(vec2 s) {
mat3 m = mat3( s.x, 0, 0, 0, s.y, 0, 0, 0, 1);
return m;
}

void main(){
vec2 position = vec2(0.0,0.0);
vec2 scale = vec2(0.5,0.5);
float rotation = 30.0;
float r = rotation/180.0*3.14159;
vec2 size = vec2(640.0,480.0);

mat3 mt = makeTranslation( translation );
mat3 mr = makeRotation( r );
mat3 ms = makeScale( 1.0/scale );

//transform
vec3 newCoord = vec3(v_texCoord.xy,1.0);
newCoord = mt*newCoord;
newCoord = mr*ms*vec3(newCoord.x - 0.5, newCoord.y - 0.5,0.0) + vec3(0.5, 0.5, 0.0);

gl_FragColor = texture2D(s_texture, vec2(newCoord.x, newCoord.y) );
}
``````

``````//transform
float fy = 0.5*(1.0 - size.y*1.0/size.x);
newCoord.y = (newCoord.y-0.5)*size.y/size.x+fy;
newCoord = mt*newCoord;
"
newCoord = mr*ms*vec3(newCoord.x - 0.5, newCoord.y - 0.5,0.0) + vec3(0.5, 0.5, 0.0);
newCoord.y = (newCoord.y+0.5)*size.x/size.y-fy;
``````