WebGL Line Drawing - Create

by soulwire

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drawing App</title>
    <style>
        canvas {
            border: 1px solid #000;
            display: block;
            margin: 20px auto;
        }
        button {
            display: block;
            margin: 20px auto;
        }
    </style>
</head>
<body>
<canvas id="drawingCanvas"></canvas>
<div id="counter"></div>
<button id="downloadButton">Download</button>

<script>
    const canvas = document.getElementById('drawingCanvas');
    const counter = document.getElementById('counter');
    const downloadButton = document.getElementById('downloadButton');
    const ctx = canvas.getContext('2d');

    // Set canvas size
    canvas.width = 800;
    canvas.height = 600;

    // Drawing state
    let isDrawing = false;
    let lastPoint = null;
    let segmentCounter = 0;

    // Map a segment index to an RGB color
    function getSegmentColor(index) {
        const r = Math.floor(index / (256 * 256)) % 256;
        const g = Math.floor(index / 256) % 256;
        const b = index % 256;
        return `rgb(${r},${g},${b})`;
    }

    // Convert a color string to a style object
    function getColorStyle(index) {
        const r = Math.floor(index / (256 * 256)) % 256;
        const g = Math.floor(index / 256) % 256;
        const b = index % 256;
        return `rgba(${r},${g},${b},1)`;
    }

    // Handle mouse down
    canvas.addEventListener('mousedown', (e) => {
        isDrawing = true;
        lastPoint = { x: e.offsetX, y: e.offsetY };
    });

    // Handle mouse move
    canvas.addEventListener('mousemove', (e) => {
        if (!isDrawing) return;

        const currentPoint = { x: e.offsetX, y: e.offsetY };
        const distance = Math.sqrt(
            Math.pow(currentPoint.x - lastPoint.x, 2) +
            Math.pow(currentPoint.y - lastPoint.y, 2)
        );

        if (distance > 1) {
    ...