代码:
<html>
<head>
<title>
webgl程序之从外部向着色器传值
</title>
<script type="text/javascript" src="./lib/webgl-debug.js"></script>
<script type="text/javascript" src="./lib/webgl-utils.js"></script>
<script type="text/javascript" src="./lib/cuon-utils.js"></script>
</head>
<body>
<canvas id='canvas' width="800" height="800"></canvas>
<script type="text/javascript">
//定义变量存储位置
//attribute:存储顶点位置,经常变的,无精度限定
//uniform:存储不变的值,有精度限定
var VShader="attribute vec4 a_position;\n"+
"void main(){\n"+
"gl_Position=a_position;"+
"gl_PointSize=10.0;\n"+
"}"
var FShader="precision mediump float;\n"+
"uniform vec4 u_color;\n"+
"void main(){\n"+
"gl_FragColor=u_color;\n"+
"}"
//
var canvas=document.getElementById("canvas");
var gl=getWebGLContext(canvas);
if(!gl){
console.log("获取webgl上下文失败")
}
if(!initShaders(gl,VShader,FShader)){
console.log("初始化着色器失败")
}
//获取着色器中的变量的地址
var a_position=gl.getAttribLocation(gl.program,'a_position')
var u_color=gl.getUniformLocation(gl.program,'u_color')
if(a_position<0){
console.log("获取a_position变量地址失败")
}
if(u_color<0){
console.log("获取f_color变量地址失败")
}
//将顶点位置赋给a_position变量,传4个float类型的值则为4f,或者3f...
gl.vertexAttrib4f(a_position,0,0,0,1)
//传给颜色值
var color=[255,0,0,1];
//有四个分量的矢量,float类型
gl.uniform4fv(u_color,color)
gl.clearColor(0,0,0,1)
gl.clear(gl.COLOR_BUFFER_BIT)
gl.drawArrays(gl.POINTS,0,1)
</script>
</body>
</html>
效果:
图片.png
网友评论