效果:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var webgl
// shader参数
var vsString = `
attribute vec3 a_position;
uniform float angle;
void main(){
gl_Position = vec4(a_position.x*cos(angle)-a_position.y*sin(angle),a_position.x*sin(angle)+a_position.y*cos(angle),0,1.0);
}
` // 顶点着色器字符串
var fsString = `
void main(){
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
}
` // 片元着色器字符串
function init(){
initWebgl()
initShader()
initBuffer()
draw()
}
function initWebgl(){
let webglDiv = document.getElementById('webgl_canvas')
webgl = webglDiv.getContext("webgl")
webgl.viewport(0,0,webglDiv.clientWidth,webglDiv.clientHeight)
}
function initShader(){
// 创建shader
let shaderVS = webgl.createShader(webgl.VERTEX_SHADER)
let shaderFS = webgl.createShader(webgl.FRAGMENT_SHADER)
// 绑定shader字符串
webgl.shaderSource(shaderVS,vsString)
webgl.shaderSource(shaderFS,fsString)
// 编译shader
webgl.compileShader(shaderVS)
webgl.compileShader(shaderFS)
// 判断shader是否编译成功
let program = webgl.createProgram()
webgl.attachShader(program,shaderVS)
webgl.attachShader(program,shaderFS)
// 链接program
webgl.linkProgram(program)
webgl.useProgram(program)
webgl.program = program
}
function initBuffer(){
let arr = [
0.1,0.4,0.0,
0.1,0.5,0.0,
0.2,0.4,0.0,
]
let float = new Float32Array(arr)
let buffer = webgl.createBuffer()
webgl.bindBuffer(webgl.ARRAY_BUFFER,buffer)
webgl.bufferData(webgl.ARRAY_BUFFER,float,webgl.STATIC_DRAW)
let aPosition = webgl.getAttribLocation(webgl.program,"a_position")
webgl.vertexAttribPointer(aPosition,3,webgl.FLOAT,false,0,0)
webgl.enableVertexAttribArray(aPosition)
let uAngle = webgl.getUniformLocation(webgl.program,"angle")
let angle1 = 90 * Math.PI / 180
webgl.uniform1f(uAngle,angle1)
}
function draw(){
webgl.clearColor(0.0,1.0,1.0,1.0)
webgl.clear(webgl.COLOR_BUFFER_BIT)
webgl.drawArrays(webgl.TRIANGLES,0,3)
}
</script>
</head>
<body onload="init()">
<canvas id="webgl_canvas" width="500" height="500"></canvas>
</body>
</html>
复盘总结: