<html>
<head>
<title>
点击绘制点(canvas与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')
if(a_position<0){
console.log("获取a_position变量地址失败")
}
//不同象限下颜色不同
var u_color=gl.getUniformLocation(gl.program,'u_color')
if(u_color<0){
console.log("获取f_color变量地址失败")
}
gl.clearColor(0,0,0,1)
gl.clear(gl.COLOR_BUFFER_BIT)
//注册canvas的点击事件
canvas.onmousedown=function(ev){
//获取浏览器下坐标
var x=ev.x;
var y=ev.y;
//获取canvas坐标
var rect=ev.target.getBoundingClientRect();
//获取canvas下坐标
var x_canvas=(x-rect.left)
var y_canvas=(y-rect.top)
console.log(x_canvas,y_canvas)
var x_gl=(x_canvas-canvas.width/2)/(canvas.width/2);
var y_gl=-(y_canvas-canvas.height/2)/(canvas.height/2)
console.log(x_gl,y_gl)
var color=[255,0,0,1];
if(x_gl>0&&y_gl>0){
color=[255,255,255,1]
}else if(x_gl<=0&&y_gl>0){
color=[255,255,0,1]
}else if(x_gl<=0&&y_gl<=0){
color=[255,0,0,1]
}else{
color=[0,0,255,1]
}
//传给颜色值
//有四个分量的矢量,float类型
gl.uniform4fv(u_color,color)
//将顶点位置赋给a_position变量,传4个float类型的值则为4f,或者3f...
gl.vertexAttrib4f(a_position,x_gl,y_gl,0,1)
gl.clearColor(0,0,0,1)
gl.clear(gl.COLOR_BUFFER_BIT)
gl.drawArrays(gl.POINTS,0,1)
}
</script>
</body>
</html>
图片.png
网友评论