实现目标画一个点
案例流程
具体代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>使用WebGL绘制一个点</title>
</head>
<body onl oad="onInit()">
<canvas id="webgl" width="500" height="500"></canvas>
<script id="vertexShader" type="x-shader/x-vertex">
attribute vec4 aPosition;
attribute float aSize;
void main() {
//给内置变量gl_PointSize赋值像素大小
gl_PointSize= aSize;//60.0
//顶点位置,位于坐标原点
gl_Position =aPosition; //vec4(0.0,0.0,0.0,1.0);
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
precision mediump float;//设置精度
uniform vec4 aColor;
void main() {
gl_FragColor=aColor; //vec4(0.0,1.0,0.0,1.0);
}
</script>
<script>
function onInit() {
//获取webgl
var canvas = document.getElementById('webgl');
var gl = canvas.getContext('webgl');
//-----加载着色器-----
//加载顶点着色器
var vertexShaderSource = document.getElementById('vertexShader').innerText;
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
//加载片元着色器
var fragShaderSource = document.getElementById('fragmentShader').innerText;
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragShaderSource);
gl.compileShader(fragmentShader);
//-----链接程序-----
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
//-----基本配置-----
//设置视口
gl.viewport(0, 0, canvas.width, canvas.height);
//设置屏幕背景色RGBA
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST); //开启深度检测
//-----参数赋值----
// //aPosition赋值
let aPositionVal = [0.0, 0.0, 0.0, 1.0];
let aPosition = gl.getAttribLocation(program, 'aPosition');
//attribute vec4=>Attrib4f,Attrib1fv
// gl.vertexAttrib4f(aPosition, ...aPositionVal);
gl.vertexAttrib1fv(aPosition, new Float32Array(aPositionVal));
//aSize赋值
let aSizeVal = 60.0;
let aSize = gl.getAttribLocation(program, 'aSize');
//attribute float=>Attrib1f
gl.vertexAttrib1f(aSize, aSizeVal);
//aColor赋值
let aColorVal = [1.0, 0.0, 0.0, 1.0];
let aColor = gl.getUniformLocation(program, 'aColor');
//uniform vec4=>uniform4f
gl.uniform4f(aColor, ...aColorVal);
//-----执行绘制-----
//画点
gl.drawArrays(gl.POINTS, 0, 1);
}
</script>
</body>
</html>
标签:入门,0.0,webgl,笔记,program,-----,aPosition,var,gl
From: https://www.cnblogs.com/xiaolidan00/p/17108375.html