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 = `
void main (){
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`
if (initShader(ctx, vertexSource, fragmentSource)) {
ctx.drawArrays(ctx.POINTERS, 0, 1)
}
//清除画板
// ctx.clearColor(0.0, 0.0, 0.0, 1.0)
// ctx.clear(ctx.COLOR_BUFFER_BIT)
// for (let i = 0; i < 100; i++) {
// let r = i / 1000;
// x = r * Math.cos(i)
// y = r * Math.sin(i)
// let aPosition = ctx.getAttribLocation(ctx.program, "a_Position")
// //以为就是1f,二维就是2f,三维就是3f...
// ctx.vertexAttrib2f(aPosition, x, y)
// ctx.drawArrays(ctx.POINTERS, 0, 1)
// }
window.addEventListener("click", e => {
console.log(e.clientX, e.clientY)
let middleX = window.innerWidth / 2
let middleY = window.innerHeight / 2
let x = 0
let y = 0
x = (e.clientX - middleX) / middleX
y = (middleY - e.clientY) / middleY
let aPosition = ctx.getAttribLocation(ctx.program, "a_Position")
//以为就是1f,二维就是2f,三维就是3f...
ctx.vertexAttrib2f(aPosition, x, y)
ctx.drawArrays(ctx.POINTERS, 0, 1)
})
//创建顶点阴影和像素阴影
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
}
}
效果: