美文网首页
webgl 点击绘制点

webgl 点击绘制点

作者: antlove | 来源:发表于2020-06-26 10:52 被阅读0次

index.html

<html>

<head>
    <meta lang="en">
    <meta charset="UTF-8">
    <title>点击绘制点</title>
    <script src="./cuon-utils.js"></script>
    <style>
        body{
            margin:0;
        }
        canvas{
            border:1px solid #999;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="500" height="500"></canvas>
</body>

<script>
    // 顶点着色器程序
    var VSHADER_SOURCE =`
        attribute vec4 a_Position;
        void main() {
            //设置坐标
            gl_Position = a_Position; 
            //设置尺寸
            gl_PointSize = 10.0; 
        } 
    `;

    // 片元着色器
    var FSHADER_SOURCE =`
        void main() {
            //设置颜色
            gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
        }
    `;


    // 获取canvas元素
    var canvas = document.getElementById('canvas');

    // 获取绘制二维上下文
    var gl = canvas.getContext('webgl');
    
    initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE);
    
    clear();

    var points = [];
    canvas.addEventListener('click', (e) => {
        var pos = getClickedPosOnCanvas(canvas, e.clientX, e.clientY);
        points.push(pos);
        clear();
        var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
        points.forEach(p => {
            gl.vertexAttrib2f(a_Position, p.x, p.y);
            /* 绘制一个点 */
            gl.drawArrays(gl.POINTS, 0, 1);
        });
    });
    
    function getClickedPosOnCanvas(canvas, clientX, clientY) {
        var rect = canvas.getBoundingClientRect();
        var halfCanvasWidth = canvas.width / 2;
        var halfCanvasHeight = canvas.height / 2;
        var x = (clientX - rect.left - halfCanvasWidth) / halfCanvasWidth;
        var y = (halfCanvasHeight - (clientY - rect.top)) / halfCanvasHeight;
        return {x, y};
    }
    
    function clear() {
        gl.clearColor(0, 0, 0, 1);
        gl.clear(gl.COLOR_BUFFER_BIT);
    }
</script>

cuon-utils.js

// cuon-utils.js (c) 2012 kanda and matsuda
/**
 * Create a program object and make current
 * @param gl GL context
 * @param vshader a vertex shader program (string)
 * @param fshader a fragment shader program (string)
 * @return true, if the program object was created and successfully made current 
 */
function initShaders(gl, vshader, fshader) {
  var program = createProgram(gl, vshader, fshader);
  if (!program) {
    console.log('Failed to create program');
    return false;
  }

  gl.useProgram(program);
  gl.program = program;

  return true;
}

/**
 * Create the linked program object
 * @param gl GL context
 * @param vshader a vertex shader program (string)
 * @param fshader a fragment shader program (string)
 * @return created program object, or null if the creation has failed
 */
function createProgram(gl, vshader, fshader) {
  // Create shader object
  var vertexShader = loadShader(gl, gl.VERTEX_SHADER, vshader);
  var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fshader);
  if (!vertexShader || !fragmentShader) {
    return null;
  }

  // Create a program object
  var program = gl.createProgram();
  if (!program) {
    return null;
  }

  // Attach the shader objects
  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);

  // Link the program object
  gl.linkProgram(program);

  // Check the result of linking
  var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  if (!linked) {
    var error = gl.getProgramInfoLog(program);
    console.log('Failed to link program: ' + error);
    gl.deleteProgram(program);
    gl.deleteShader(fragmentShader);
    gl.deleteShader(vertexShader);
    return null;
  }
  return program;
}

/**
 * Create a shader object
 * @param gl GL context
 * @param type the type of the shader object to be created
 * @param source shader program (string)
 * @return created shader object, or null if the creation has failed.
 */
function loadShader(gl, type, source) {
  // Create shader object
  var shader = gl.createShader(type);
  if (shader == null) {
    console.log('unable to create shader');
    return null;
  }

  // Set the shader program
  gl.shaderSource(shader, source);

  // Compile the shader
  gl.compileShader(shader);

  // Check the result of compilation
  var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  if (!compiled) {
    var error = gl.getShaderInfoLog(shader);
    console.log('Failed to compile shader: ' + error);
    gl.deleteShader(shader);
    return null;
  }

  return shader;
}

/** 
 * Initialize and get the rendering for WebGL
 * @param canvas <cavnas> element
 * @param opt_debug flag to initialize the context for debugging
 * @return the rendering context for WebGL
 */
function getWebGLContext(canvas, opt_debug) {
  // Get the rendering context for WebGL
  var gl = WebGLUtils.setupWebGL(canvas);
  if (!gl) return null;

  // if opt_debug is explicitly false, create the context for debugging
  if (arguments.length < 2 || opt_debug) {
    gl = WebGLDebugUtils.makeDebugContext(gl);
  }

  return gl;
}

image.png

相关文章

网友评论

      本文标题:webgl 点击绘制点

      本文链接:https://www.haomeiwen.com/subject/caiyfktx.html