Open In App

How to Handle Mouse and Keyboard Input in WebGL?

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

WebGL in web development is a JavaScript API that allows for the rendering of interactive 2D and 3D graphics within a web browser without the need for plugins. Handling mouse and keyboard input in WebGL involves capturing these inputs through event listeners and using them to manipulate the graphics rendered on the canvas. This interaction enables the creation of dynamic and responsive visual experiences, where user actions directly influence the content and behavior of the graphics.

These are the following events that we are going to handle:

Handling Mouse Input in WebGL

In this approach, we are using WebGL's 2D context to handle mouse input on a canvas. The script captures mouse events to draw red circles on the canvas and displays the current mouse position on the screen and in the console. It also provides a button to clear the canvas and reset the displayed mouse coordinates.

Example: The below example handles mouse input in WebGL.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>Example 1</title>
    <style>
        canvas {
            border: 1px solid black;
        }

        .controls {
            margin-bottom: 10px;
        }

        #info {
            margin-top: 10px;
            font-family: Arial, sans-serif;
        }
    </style>
</head>

<body>
    <div class="controls">
        <button id="clear">Clear Canvas</button>
    </div>
    <canvas id="webgl-canvas" width="800" height="600"></canvas>
    <div id="info">Mouse Position: X: 0, Y: 0</div>
    <script src="script.js"></script>
</body>

</html>
JavaScript
// script.js

const canvas = document.getElementById('webgl-canvas');
const gl = canvas.getContext('2d');
const info = document.getElementById('info');
let drawCircles = true;
gl.fillStyle = 'black';
gl.fillRect(0, 0, canvas.width, canvas.height);
function drawCircle(x, y, radius, color) {
    gl.beginPath();
    gl.arc(x, y, radius, 0, 2 * Math.PI, false);
    gl.fillStyle = color;
    gl.fill();
}
function clearCanvas() {
    gl.clearRect(0, 0, canvas.width, canvas.height);
    gl.fillStyle = 'black';
    gl.fillRect(0, 0, canvas.width, canvas.height);
}
function updateInfo(x, y) {
    info.textContent = `Mouse Position: X: ${x}, Y: ${y}`;
}
canvas.addEventListener('mousedown', (event) => {
    if (drawCircles) {
        const rect = canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        drawCircle(x, y, 20, 'red');
        updateInfo(x, y);
        console.log(`Mouse down at (${x}, ${y})`);
    }
});
canvas.addEventListener('mousemove', (event) => {
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    updateInfo(x, y);
    console.log(`Mouse move at (${x}, ${y})`);
    if (drawCircles) {
        clearCanvas();
        drawCircle(x, y, 20, 'red');
    }
});
document.getElementById('clear')
		.addEventListener('click', () => {
    clearCanvas();
    updateInfo(0, 0);
});

Output:

1-ezgifcom-resize-(1)(1)

Handling Keyboard Input in WebGL

In this approach, we are using the 2D context of a canvas element to handle keyboard input and move a blue square around the canvas. Arrow key presses adjust the position of the square, with real-time updates displayed on the screen. A reset button re-centers the square and clears the key information.

Example: The below example handles keyboard input in WebGL.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>WebGL Keyboard Input Example</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        canvas {
            border: 1px solid black;
        }

        .controls {
            margin-bottom: 10px;
        }

        #info {
            margin-top: 10px;
            font-family: Arial, sans-serif;
        }
    </style>
</head>

<body>
    <div class="controls">
        <button id="reset">Reset Position</button>
    </div>
    <div id="container">
        <canvas id="webgl-canvas" width="600" height="400"></canvas>
        <div id="info">Current Key: None</div>
    </div>
    <script src="script.js"></script>
</body>

</html>
JavaScript
const canvas = document.getElementById('webgl-canvas');
const gl = canvas.getContext('2d');
const info = document.getElementById('info');
let squareX = canvas.width / 2;
let squareY = canvas.height / 2;
const squareSize = 100;
const moveAmount = 10;
function drawSquare(x, y) {
    gl.clearRect(0, 0, canvas.width, canvas.height);
    gl.fillStyle = 'blue';
    gl.fillRect(x - squareSize / 2, y - squareSize / 2, squareSize, squareSize);
}
function updateInfo(key) {
    info.textContent = `Current Key: ${key}`;
}
document.addEventListener('keydown', (event) => {
    switch (event.key) {
        case 'ArrowUp':
            squareY -= moveAmount;
            updateInfo('ArrowUp');
            break;
        case 'ArrowDown':
            squareY += moveAmount;
            updateInfo('ArrowDown');
            break;
        case 'ArrowLeft':
            squareX -= moveAmount;
            updateInfo('ArrowLeft');
            break;
        case 'ArrowRight':
            squareX += moveAmount;
            updateInfo('ArrowRight');
            break;
        default:
            updateInfo('None');
            break;
    }
    drawSquare(squareX, squareY);
});
document.getElementById('reset').addEventListener('click', () => {
    squareX = canvas.width / 2;
    squareY = canvas.height / 2;
    drawSquare(squareX, squareY);
    updateInfo('None');
});
drawSquare(squareX, squareY);

Output:

2

Next Article

Similar Reads