webgl-画三角形
html
<!DOCTYPE html>
<head>
<style>
*{
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id = 'webgl'>
您的浏览器不支持HTML5,请更换浏览器
</canvas>
<script src="./main.js"></script>
</body>
main.js
let canvas = document.getElementById('webgl')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
let ctx = canvas.getContext('webgl')
//创建顶点资源和像素资源(颜色)
let vertexSource = `
attribute vec2 a_Position;
void main() {
gl_Position = vec4(a_Position, 0.0, 1.0);
gl_PointSize = 10.0;
}
`
let fragmentSource = `
precision mediump float;
uniform vec3 u_color;
void main (){
gl_FragColor = vec4(u_color, 1.0);
}
`
if (initShader(ctx, vertexSource, fragmentSource)) {
//设置颜色
let color = ctx.getUniformLocation(ctx.program, "u_color2")
ctx.uniform3f(color, 1.0, 0.0, 0.0)
//画三角形
let vertexs = [
-0.5, 0.0,
0.5, 0.0,
0.0, 0.5
]
let float32Array = new Float32Array(vertexs)
//创建buffer
let buffer = ctx.createBuffer()
//绑定buffer
ctx.bindBuffer(ctx.ARRAY_BUFFER, buffer)
//往buffer中填充值,并指定数据用途
ctx.bufferData(ctx.ARRAY_BUFFER, float32Array, ctx.STATIC_DRAW)
//获取vertexShader指定变量内存
let a_Position = ctx.getAttribLocation(ctx.program, "a_Position")
ctx.vertexAttribPointer(a_Position, 2, ctx.FLOAT, false, 0, 0)
//确认吧带有数据的buffer赋值给a_Position
ctx.enableVertexAttribArray(a_Position);
ctx.drawArrays(ctx.TRIANGLES, 0, 3)
}
//创建顶点阴影和像素阴影
function createShader(ctx, type, source) {
//创建shader
let shader = ctx.createShader(type)
//绑定
ctx.shaderSource(shader, source)
//编译shader
ctx.compileShader(shader)
//获取编译结果
let compiler = ctx.getShaderParameter(shader, ctx.COMPILE_STATUS)
if (compiler) {
return shader
} else {
let log = ctx.getShaderInfoLog(shader)
console.log("compile shaders error", log)
//删除异常的shader,防止内存泄露
ctx.deleteShader(shader)
return null
}
}
function createProgram(ctx, vertexShader, fragmentShader) {
//创建program
let program = ctx.createProgram()
if (!program) {
return null
}
//点资源和像素资源合并
ctx.attachShader(program, vertexShader)
ctx.attachShader(program, fragmentShader)
ctx.linkProgram(program)
//获取linked的结果
let linked = ctx.getProgramParameter(program, ctx.LINK_STATUS)
if (linked) {
return program
} else {
//获取link错误信息
let log = ctx.getProgramInfoLog(program)
console.log("link program error", log)
//删除防止内存泄漏
ctx.delete(program)
ctx.deleteShader(vertexShader)
ctx.deleteShader(fragmentShader)
return null
}
}
function initShader(ctx, vertexSource, fragmentSource) {
let vertexShader = createShader(ctx, ctx.VERTEX_SHADER, vertexSource)
let fragmentShader = createShader(ctx, ctx.FRAGMENT_SHADER, fragmentSource)
let program = createProgram(ctx, vertexShader, fragmentShader)
if (program) {
ctx.useProgram(program)
//挂载到ctx
ctx.program = program
return true
} else {
return false
}
}
效果图