background/漂移动画.html

85 lines
2.2 KiB
HTML
Raw Permalink Normal View History

2024-01-13 18:54:32 +00:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="webgl" width="500" height="500"></canvas>
<script>
const gl = document.getElementById('webgl').getContext('webgl');
const vertexShaderSource = "" +
"attribute vec4 apos;" +
"uniform mat4 mat;" +
"void main(){" +
" gl_Position = mat * apos;" +
"}";
const fragmentShaderSource = "" +
"void main(){" +
" gl_FragColor = vec4(1.0,0.0,0.0,1.0);" +
"}";
const program = initShader(gl,vertexShaderSource,fragmentShaderSource);
const aposlocation = gl.getAttribLocation(program,'apos');
const matlocation = gl.getUniformLocation(program,'mat');
const data = new Float32Array([
0.0,0.0,
-.3,-.3,
.3,-.3
]);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,buffer);
gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
gl.vertexAttribPointer(aposlocation,2,gl.FLOAT,false,0,0);
gl.enableVertexAttribArray(aposlocation);
let Tx = 0.1; //x坐标的位置
let Ty = 0.1; //y坐标的位置
let Tz = 0.0; //z坐标的位置
let Tw = 1.0; //差值
function run () {
Tx += 0.01
Ty += 0.01
const mat = new Float32Array([
1.0,0.0,0.0,0.0,
0.0,1.0,0.0,0.0,
0.0,0.0,1.0,0.0,
Tx,Ty,Tz,Tw,
]);
if(Tx > 0.8){
Tx = -0.8
}
if(Ty > 0.8){
Ty = -0.8
}
gl.uniformMatrix4fv(matlocation,false,mat);
gl.drawArrays(gl.TRIANGLES,0,3);
// 使用此方法实现一个动画
requestAnimationFrame(run)
}
run()
function initShader(gl,vertexShaderSource,fragmentShaderSource){
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(vertexShader,vertexShaderSource);
gl.shaderSource(fragmentShader,fragmentShaderSource);
gl.compileShader(vertexShader);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program,vertexShader);
gl.attachShader(program,fragmentShader)
gl.linkProgram(program);
gl.useProgram(program);
return program;
}
</script>
</body>
</html>