WebGL JavaScript

Change the Color on a Mouse Click

This JavaScript program demonstrates hwo to change the color of the screen in WebGL program when the mouse is clicked.

ChangeColorOnClick.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's WebGL</title>

    <script type="text/javascript">
      var qGL;

      function Initialization() {
        // Get the WebGL Context
        var qCanvas = document.querySelector("#idCanvasWebGL");
        qGL = qCanvas.getContext("webgl");
        // Clear the screen and set it to black, initially
        qGL.clearColor(.5, 0.8, 0.5, 1);
        qGL.clear(qGL.COLOR_BUFFER_BIT);

        // Set the event listener to trigger when the cnavas is clicked
        qCanvas.addEventListener("click", SwapColor, false);
      }

      function SwapColor() {
        qGL.clearColor(Math.random(), Math.random(), Math.random(), 1.0);
        qGL.clear(qGL.COLOR_BUFFER_BIT);
      }
    </script>
  </head>
  <body onload="Initialization()">
    <p>Click the screen to change the color</p>
    <canvas id="idCanvasWebGL" width="400" height="400" style="border:1px solid red"></canvas>
  </body>
</html>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.