How to extend the background to the entire webpage?

Blockquote

I set .matrix-background to position: fixed and adjusted width, height, and top properties to make it cover the full page.
I used document.body.scrollHeight in JavaScript to calculate the page height, hoping the animation would cover the entire page.

I want the matrix background on the whole webpage even if i scroll down till the end but i'm only getting the background till the first container 

here is my index.html Matrix background

 .matrix-background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            pointer-events: none;
            z-index: -1;
            overflow: hidden;
        }

and this is my script for the background

const characters =
“ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789”;
const matrixBackground = document.querySelector(‘.matrix-background’);

                function createMatrix() {
                    const span = document.createElement('span');
                    span.style.position = 'absolute';
                    span.style.color = 'green';
                    span.style.fontSize = '20px';
                    span.style.whiteSpace = 'nowrap';
                    span.style.opacity = Math.random();
                    span.textContent = characters.charAt(Math.floor(Math.random() * 
         characters.length));
            
                     const x = Math.random() * window.innerWidth;
                     span.style.left = `${x}px`;
                     span.style.top = `-${Math.random() * 100}px`;  // Start just 
            above the viewport
                     matrixBackground.appendChild(span);
            
                      // The span falls down to cover the visible viewport and beyond 
       to mimic continuous effect
                       const fallDuration = Math.random() * 3 + 2;
                       span.animate([{ transform: 'translateY(0)' }, { transform: 
         `translateY(${window.innerHeight * 2}px)` }], {
                           duration: fallDuration * 1000,
                          easing: 'linear',
                           iterations: 1,
                          fill: 'forwards',
                      });
            
                      setTimeout(() => {
                           span.remove();
                       }, fallDuration * 1000);
                   }

                 setInterval(createMatrix, 100);
                </script>

Blockquote

Chrome Extension: SpeechSynthesis does not output sound on the first call

I am trying to output sound using SpeechSynthesis. I pre-defined speechSynthesis and SpeechSynthesisUtterance:

TTS = window.speechSynthesis;
utter = new SpeechSynthesisUtterance();
...

let voices = speechSynthesis.getVoices();
this.utter.voice = voices[3];
this.utter.name = voices[3].name;
this.utter.lang = voices[3].lang;
this.utter.voiceURI = voices[3].voiceURI;

When I try to output sound like:

this.utter.text = "say something";
this.TTS.speak(this.utter);

There is no output the first time I call TTS.speak, but this.TTS.speaking becomes true. It happens after it doesn’t play any speech for several minutes.

If I play it a second time, it works:

this.TTS.speak(this.utter);
this.TTS.cancel();
this.TTS.speak(this.utter);

Also, if I make a copy of this.utter and play that copy, it works as well:

let utterance = new SpeechSynthesisUtterance(this.utter.text);
utterance.voice = this.utter.voice;
utterance.name = this.utter.name;
utterance.lang = this.utter.lang;
utterance.voiceURI = this.utter.voiceURI;
this.TTS.speak(utterance);

I found speechSynthesis.speak() without user activation is no longer allowed since M71, around December 2018. However, in this case, each TTS.speak call is triggered by a play button.

Show only elements with a specific id (determened in the url)

I’ve been working on a coding project and I have been trying to have multiple “pages” in one html file (e.g. awsomesauce.com/page.html#videos and showing only the videos section) while having the same navbar and so far javascript has let me down. Any ideas?

<script>
// Get the current URL (awsomesauce.com/page#videos in this instance)
let url = window.location.href;
// Get the length of the current URL
let urlLength = window.location.href.length;
// Extract the portion of the URL starting from index 21
let  = url.substr(21, urlLength);
</script>

CORS error on Azure Storage calls from Javascript to commit chunked uploads

I want users to upload a huge file directly into Azure Storage. I have a Flask Python web app but I do not want the file to be uploaded into my web server due to size constraints.

When the user has selected the file they want to upload and clicks the upload button, the following happens:

  1. An API is called that generates a SAS URL and a blob name to assign to the file to be uploaded. The code that generates both is:
    blob_name = str(uuid.uuid4())  

    container_name = os.environ[default_container_name_setting]

    sas = generate_blob_sas(account_name=service.account_name,
                            account_key=access_key,
                            container_name=container_name,
                            blob_name=blob_name,
                            permission=BlobSasPermissions(write=True, read=True, create=True),
                            expiry=datetime.utcnow() + timedelta(hours=2)) 

    sas_url = 'https://' + service.account_name + '.blob.core.windows.net/' + container_name + '/' + blob_name + '?' + sas
    return sas_url, blob_name
  1. The file is then uploaded in chunks:
const chunkSize = 1024 * 1024 * 20; 
const totalChunks = Math.ceil(file.size / chunkSize);
const blockIds = []; // Array to hold block IDs

for (let i = 0; i < totalChunks; i++) {
    const start = i * chunkSize;
    const end = Math.min(start + chunkSize, file.size);
    const chunk = file.slice(start, end);
    const blockId = btoa("block-" + i); // Base64 encode block ID
    blockIds.push(blockId);

    // Upload each chunk
    const uploadResponse = await fetch(sas_url + "&comp=block&blockid=" + blockId, {
        method: "PUT",
        headers: {
            "x-ms-blob-type": "BlockBlob",
            "Content-Type": file.type
        },
        body: chunk
    });

    if (!uploadResponse.ok) {
        return false;
    }
}

It works up to this point. However, the next step is to tell Azure to put the chunks together:

const commitResponse = await fetch(sas_url + "&comp=commitBlockList", {
    method: "PUT",
    headers: {
        "Content-Type": "application/xml",
        "x-ms-version": "2020-10-02",
        "Content-Length": "0"
    },
    body: `<BlockList>${blockIds.map(id => `<Latest>${id}</Latest>`).join('')}</BlockList>`
});

if (!commitResponse.ok) {
    throw new Error("Failed to commit blocks to blob.");
}

I always get a CORS error at this point:

Access to fetch at ‘https://xxx.blob.core.windows.net/container/e07d13fa-bcd6-45cf-9eea-3295e17dc567?se=2024-11-01T04%2A18%3B30Q&sp=rcw&sv=2024-11-04&sr=b&sig=CudrFGsJ1HGnYo6Bh3K7WVAabgdOAsPteWq47XKuKDI%3D&comp=commitBlockList’ from origin ‘http://localhost:4449’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

I know I have properly set the CORS in Azure Storage because the upload part works.

Under Blob Service tab, I have added my localhost origin, with allowed methods GET, POST, OPTIONS, and PUT.

I have tried regenerating another SAS Url with the retrieved Blob name but I’m still getting the CORS error.

What am I missing?

Browser console show “Uncaught ReferenceError: [functionName] is not defined”

The following code in the classic asp file (test.asp) that occurs Uncaught ReferenceError: abcFunc is not defined in browser console.

<input name="testFileList" type="hidden" value="<%=myFileList%>" id=" testFileList ">
<script type="text/javascript" language="javascript">           
refreshMyFile(document, abcFunc(document.getElementById("testFileList ")));
</script>

I try to put dim abcFunc in test.asp, it occurs Name redefined error.

I also try to change from

<script language="text/javascript">

to

<script>

It shows the same error in in Chrome console Uncaught ReferenceError: abcFunc is not defined .

If I don’t use abcFunc, no error in Chrome console. So I focus on abcFunc.

<script type="text/javascript" language="javascript">           
 refreshMyFile(document, document.getElementById("testFileList"));
</script>

However I check the abcFunc Function, the code seems normal.

Function abcFunc(byval Str)
 if Len(Str) <> 0 then
  Str = Replace(Str,Chr(59),"&#59")
  Str = Replace(Str,Chr(34),"&#34")
  Str = Replace(Str,Chr(60),"&#60")
  Str = Replace(Str,Chr(62),"&#62")
  Str = Replace(Str,Chr(13),"<br>")
  abcFunc=trim(Str)
 else
  abcFunc = ""
end if
End Function

I view these questions but don’t have idea how to solve it.

Uncaught ReferenceError: ‘functionName’ not defined

Uncaught ReferenceError – Function is not defined

Uncaught ReferenceError: [functionName] is not defined

Uncaught ReferenceError: [ function_name ] is not defined

Uncaught ReferenceError: functionis not defined error, why?

I will appreciate your advice with this issue. Thanks

Is there an alternative method for replacing the default element that appears under the mouse with an image while dragging a draggable element?

I’m working on drag-and-drop functionality in a vue.js web application where I want to replace the default drag image that appears under the mouse with a custom image. Currently, I’m using the following implementation:

const imgElement = gridField.children[0].querySelector('.applicationImage');
const imgClone = imgElement.cloneNode();

imgClone.style.width = '40px';
imgClone.style.height = '40px';
imgClone.style.pointerEvents = 'none';
imgClone.style.position = 'absolute';
imgClone.style.top = '-1000px';

this.$el.appendChild(imgClone);

event.dataTransfer.setDragImage(imgClone, 20, 20);

setTimeout(() => {
  this.$el.removeChild(imgClone);
}, 0);

for further context I use this code inside a eventListener that is set in the vue template like this:
`@dragstart=”dragAndDrop($event, ‘dragstart’)”‘

It works fine but it does feel like a unclean workaround.

I tried to look for other solutions but could not find any. Is there a better way to implement this functionality?

Thank you!

How to make several charts with the same echartsInstance using timeline?

I’m using timeline with echarts. I need to add more charts to the screen, however, using only one instance of echarts (echarts.init only once). I need to put other charts separate from timeline on the screen, I tried putting a type:“gauge” but it doesn’t work:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Exemplo de Gráfico com Timeline e Gauge</title>
        <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
        <style>
            #chart {
                width: 100%;
                height: 100vh;
            }
        </style>
    </head>
    <body>
    
    <div id="chart"></div>
    
    <script>
        const chartUse = echarts.init(document.getElementById('chart'));
    
        window.addEventListener("resize", () => {
            chartUse.resize();
        });
    
        const option = {
            baseOption: {
                timeline: {
                    axisType: 'category',
                    autoPlay: true,
                    playInterval: 2000,
                    rewind: false,
                    data: ['Jan', 'Fev', 'Mar']
                },
                grid: {
                    width: "40%",
                    height: "50%",
                    left: "5%"
                },
                xAxis: {
                    type: "category",
                    data: ["Jan", "Fev", "Mar"],
                    gridIndex: 0
                },
                yAxis: {
                    type: "value",
                    gridIndex: 0
                },
                series: [
                    {
                        // Gauge fixo, sempre visível
                        type: "gauge",
                        center: ['75%', '50%'], // Posiciona o gauge à direita
                        radius: '30%',
                        detail: { formatter: '{value}%' },
                        data: [{ value: 50, name: 'Progress' }]
                    }
                ]
            },
            options: [
                // Opção 1: Gráfico de barras para janeiro
                {
                    series: [
                        {
                            type: "bar",
                            xAxisIndex: 0,
                            yAxisIndex: 0,
                            data: [10, 20, 30]
                        }
                    ]
                },
                // Opção 2: Gráfico de barras para fevereiro
                {
                    series: [
                        {
                            type: "bar",
                            xAxisIndex: 0,
                            yAxisIndex: 0,
                            data: [15, 25, 35]
                        }
                    ]
                },
                // Opção 3: Gráfico de barras para março
                {
                    series: [
                        {
                            type: "bar",
                            xAxisIndex: 0,
                            yAxisIndex: 0,
                            data: [20, 30, 40]
                        }
                    ]
                }
            ]
        };
    
        chartUse.setOption(option);
    </script>
    
    </body>
    </html>
     

In other words, using just one instance (chartUse) I need to place other charts using the timeline in this same instance. How can I adjust baseOption and options to achieve this result?

Toogle then visibility of a div by hovering on the corresponding nav-item with JS

I have a mega-menu-dropdown which has 2 columns. Column 1 has a list of terms and by hovering on the terms (mouse-in) the corresponding div should become visible.

Also the first combination of list-item and corresponding div should be visible when entering the dropdown.

This is what I have so far:

document.addEventListener("DOMContentLoaded", function(event) {
  let ktnavList = document.querySelector(".mm-dropdown--nav").children;
  let ktcatList = document.querySelector(".mm-dropdown--cat").children;
    for (let i=0; i<ktnavList.length; i++) {
      let li = ktnavList[i];
      let cat = ktcatList[i];
      li.addEventListener('mouseenter', () => {
      cat.classList.toggle('active-item');
      });
      li.addEventListener('mouseleave', () => {
      cat.classList.toggle('active-item');
      });
   };
});

I can toogle all items except the first one.
I need the first div to hide when hovering on the second list-item but to become visible again when entering the dropdown again (that should be the standard state of the dropdown).

I also think I don’t need the ‘mouseleave’ part. Because it will prevent the user to access the contents of the divs (more navigation elements).

Desired behavior would be that if I hover above one list item all the other divs belonging to the other list-items would hide (toogle class ‘active-item’).

I don’t know how to toggle all other divs that are not attached to the ‘mouseenter’.

Thanks in advance.

How do I determine the package that installed a javascript executable?

I have file called node_modules/.bin/openapi. I was trying to figure out:

  • where the source is for that; and
  • what package created it.

I have solved the problem and I now want to know how to do this efficiently. The file node_modules/.bin/openapi is created by the @redocly/cli package. Inside the package.json it has:

"bin": {
  "openapi": "bin/cli.js",
  "redocly": "bin/cli.js"
},

The file node_modules/@redocly/cli/bin/cli.js is very simple:

#!/usr/bin/env node
  
require('../lib/index');

That’s the same file that was getting installed into node_modules/.bin/openapi.

But how can you efficiently, given an install artifact like node_modules/.bin/openapi, trace back to the package that created it?

I am getting a buffer error when using a Typescript RPC library in Vite, Vue

I am using a typescript library that does RPC calls for a blockchain. I am trying to use it in my Javascript and Vue project with Vite bundler.

I have tried install polyfills, buffer etc but somehow I still get the error mentioned below.

This is the library : https://github.com/VerusCoin/verusd-rpc-ts-client

vdxf.js:11 Uncaught ReferenceError: Buffer is not defined
    at node_modules/verus-typescript-primitives/dist/constants/vdxf.js (vdxf.js:11:59)
    at __require (chunk-BUSYA2B4.js?v=8da589e3:3:50)
    at node_modules/verus-typescript-primitives/dist/vdxf/index.js (index.js:20:16)
    at __require (chunk-BUSYA2B4.js?v=8da589e3:3:50)
    at node_modules/verus-typescript-primitives/dist/vdxf/classes/Challenge.js (Challenge.js:4:13)
    at __require (chunk-BUSYA2B4.js?v=8da589e3:3:50)
    at node_modules/verus-typescript-primitives/dist/vdxf/classes/index.js (index.js:4:19)
    at __require (chunk-BUSYA2B4.js?v=8da589e3:3:50)
    at node_modules/verus-typescript-primitives/dist/index.js (index.js:22:14)
    at __require (chunk-BUSYA2B4.js?v=8da589e3:3:50)
node_modules/verus-typescript-primitives/dist/constants/vdxf.js @ vdxf.js:11
__require @ chunk-BUSYA2B4.js?v=8da589e3:3
node_modules/verus-typescript-primitives/dist/vdxf/index.js @ index.js:20
__require @ chunk-BUSYA2B4.js?v=8da589e3:3
node_modules/verus-typescript-primitives/dist/vdxf/classes/Challenge.js @ Challenge.js:4
__require @ chunk-BUSYA2B4.js?v=8da589e3:3
node_modules/verus-typescript-primitives/dist/vdxf/classes/index.js @ index.js:4
__require @ chunk-BUSYA2B4.js?v=8da589e3:3
node_modules/verus-typescript-primitives/dist/index.js @ index.js:22
__require @ chunk-BUSYA2B4.js?v=8da589e3:3
node_modules/verusd-rpc-ts-client/lib/VerusdRpcInterface.js @ VerusdRpcInterface.js:16
__require @ chunk-BUSYA2B4.js?v=8da589e3:3
node_modules/verusd-rpc-ts-client/lib/index.js @ index.js:30
__require @ chunk-BUSYA2B4.js?v=8da589e3:3
(anonymous) @ index.js:33
Show 8 more frames
Show less

Rails 7.1.3 – my javascript function is not found when invoking window.onload on page load

I have an application on Rails 7.1.3.4, upgraded from Rails 6. I am in the process of converting to using import maps for Javascript that the application uses. I am not using Turbo and Stimulus in this application. On one of my pages I invoke window.onload to run a javascript function residing in one of my javascript files. When I run the page, I get an error in the console saying that the function is not defined. I checked and the javascript file is loaded in the page, so I think that I’m defining my import maps and imports properly. I cannot figure out why the function cannot be accessed. Any help appreciated!

Here’s the error message that I get in the console when the page is loaded:

Uncaught ReferenceError: setConfPicksDsply is not defined
at window.onload (edit:2163:28)

Here’s the relevant code in the view(it’s at the end of the view file):

</div>
<%= javascript_tag "window.onload = function(){setConfPicksDsply();}" %>
<% end %>

The function setConfPicksDsply() resides in the file confnosprdpicks.js:

function setConfPicksDsply() {  
    // console.log("entering setConfPicksDsply()");
    set_page_info_dialog("info_button");
    setConfidencePoolSchedDsply();
    set_picks_dsply();
    set_sched_pnts_picked();
    var nTimeToNextGame = time_to_next_game();
    // console.log(nTimeToNextGame);
;   if (nTimeToNextGame > 0)
        {
            // console.log("about to call setTimeout");
            setTimeout(gm_expiration_confidence,time_adjusted_for_max_settimeout_val(nTimeToNextGame));
        }
}

The javascript file in the HTML is:

<link rel="modulepreload" href="/assets/confnosprdpicks-60401ca8e1ca41b15e45331a22235f5dae41ed4cf88beda020a167403337da36.js">

and I can see that the function is in the file when I open it. Any ideas on how I can get the function to be recognized and run? Thanks!

Nesting two functions — syntax issue or improper code?

I have two functions that I’m trying to combine but having issues with it properly rendering and (more importantly) functioning as expected on the page. I suspect it’s a syntax issue, but I’m new to coding so I could very well be making a newbie mistake.

Fyi – function1 is displaying/working as expected by itself on page1. Function2 is working displaying as expected on page 2 when I have just that function within the script tag(s) and separately have the input tags below within the head/body tags. The issue I’m encountering is when I try to combine [i.e.- nest]the 2 functions on a single page while also pulling the input tags from function2 into the innerHTML of the newly-nested function(s).

Currently, a user can enter an address into the addy2 field and it will auto-complete via an integrated API call (which works perfectly on it’s own/as is); my goal is to retain the auto-complete functionality but also give the user the option to click either radio button 1 or radio button 2 and have either the 1st address or the 2nd address (respectively) populate in the addy2 text field. Is this possible to do?!?

function numeroUno() {
    const {
        addy1: e,
        addy2: t
    } = appState;
    document.getElementById("content").innerHTML = `n    <h1>Title Placeholder</h1>n    <div>n      <label for="addy1">Address 1</label>n      <input type="text" id="addy1" value="${e}" required>n    </div>n    <div>n      <label for="addy2">Address 2</label>n      <input type="text" id="addy2" value="${t}" required>n    </div>n    <button id="calc-btn">Calculate</button>n  `, initAutocomplete()({
    calcBtn: calcDist
    })
}


function numeroDos(radioButtonId, textFieldId, textToPopulate) {
  // Get the radio button and text field elements
  const radioButton = document.getElementById(radioButtonId);
  const textField = document.getElementById(textFieldId);

  // Select the radio button
  radioButton.checked = true;

  // Populate the text field
  textField.value = textToPopulate;
  document.getElementById("content").innerHTML = `n    <div class="mb-4">n     <input type="text" id="addy1">n     <input type="radio" id="radio1" name="myRadio" onclick="numeroDos('radio1', 'addy1', '123 address st, City, ST, Zip')">n    <label for="radio1">Radio 1</label>n    <input type="radio" id="radio2" name="myRadio" onclick="numeroDos('radio2', 'addy1', '456 address st, City, ST, Zip')">n    <label for="radio2">Radio 2</label>n    </div>n  ` 
}

Hope that all makes sense. Thank you in advance for any/all help!

Elegant way to use a big Promise.all?

I am working on a game and I have a spot in the code where I load all the resources in parallel. Currently it looks something like this:

let [
    grassTexture,
    stoneTexture,
    waterTexture,
    skyTexture,
    sandTexture,
    woodTexture,
    carpetTexture,
    paperTexture,
    steelTexture
] = await Promise.all([
    loadGrassTexture(),
    loadStoneTexture(),
    loadWaterTexture(),
    loadSkyTexture(),
    loadSandTexture(),
    loadWoodTexture(),
    loadCarpetTexture(),
    loadPaperTexture(),
    loadSteelTexture()
])

but that doesn’t strike me as particularly well-designed since it’s easy to mess up the order and it would be better if the result was on the same line with the respective function call. Another option I see is this:

let grassTexture = loadGrassTexture()
let stoneTexture = loadStoneTexture()
let waterTexture = loadWaterTexture()
let skyTexture = loadSkyTexture()
let sandTexture = loadSandTexture()
let woodTexture = loadWoodTexture()
let carpetTexture = loadCarpetTexture()
let paperTexture = loadPaperTexture()
let steelTexture = loadSteelTexture()

await grassTexture
await stoneTexture
await waterTexture
await skyTexture
await sandTexture
await woodTexture
await carpetTexture
await paperTexture
await steelTexture

but that’s not much better. Is there some idiomatic way to do this?

how to import THREE.InfiniteGridHelper

When attempting to use THREE.InfiniteGridHelper there doesn’t seem to be a way to import the code that doesn’t generate an error. Even copying and pasting the code does not work.

Currently I have the code copied and pasted into my main.js page and this gives the error it gives

Uncaught TypeError: “InfiniteGridHelper” is read-only
http://127.0.0.1:5000/static/main.js:10

I have also tried pasting the code into its own InfiniteGridHelper.js page to be run locally , importing the code from https://mevedia.com/share/InfiniteGridHelper.js?c, import maps, and using a regular script tag. the results tend to cycle between errors like

Uncaught TypeError: THREE.InfiniteGridHelper is not a constructor
http://127.0.0.1:5000/static/main.js:142

“SyntaxError: import declarations may only appear at top level of a module”

Uncaught SyntaxError: The requested module ‘http://127.0.0.1:5000/static/InfiniteGridHelper.js’ doesn’t provide an export named: ‘InfiniteGridHelper’

Uncaught ReferenceError: THREE is not defined
http://127.0.0.1:5000/static/InfiniteGridHelper.js:3

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mevedia.com/share/InfiniteGridHelper.js?c. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

There is a forum on this library that seems to have been abandoned but it looks like other people were able to get it to work and it also seems to work on codepen. I’m just not able to figure out a way to get it to run locally.

import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper)


THREE.InfiniteGridHelper = function InfiniteGridHelper( size1, size2, color, distance, axes = 'xzy' ) {

    color = color || new THREE.Color( 'white' );
    size1 = size1 || 10;
    size2 = size2 || 100;

    distance = distance || 8000;



    const planeAxes = axes.substr( 0, 2 );

    const geometry = new THREE.PlaneBufferGeometry( 2, 2, 1, 1 );

    const material = new THREE.ShaderMaterial( {

        side: THREE.DoubleSide,

        uniforms: {
            uSize1: {
                value: size1
            },
            uSize2: {
                value: size2
            },
            uColor: {
                value: color
            },
            uDistance: {
                value: distance
            }
        },
        transparent: true,
        vertexShader: `
           
           varying vec3 worldPosition;
           
           uniform float uDistance;
           
           void main() {
           
                vec3 pos = position.${axes} * uDistance;
                pos.${planeAxes} += cameraPosition.${planeAxes};
                
                worldPosition = pos;
                
                gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
           
           }
           `,


        fragmentShader: `
           
           varying vec3 worldPosition;
           
           uniform float uSize1;
           uniform float uSize2;
           uniform vec3 uColor;
           uniform float uDistance;
            
            
            
            float getGrid(float size) {
            
                vec2 r = worldPosition.${planeAxes} / size;
                
                
                vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
                float line = min(grid.x, grid.y);
                
            
                return 1.0 - min(line, 1.0);
            }
            
           void main() {
           
                
                  float d = 1.0 - min(distance(cameraPosition.${planeAxes}, worldPosition.${planeAxes}) / uDistance, 1.0);
                
                  float g1 = getGrid(uSize1);
                  float g2 = getGrid(uSize2);
                  
                  
                  gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));
                  gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);
                
                  if ( gl_FragColor.a <= 0.0 ) discard;
                
           
           }
           
           `,

        extensions: {
            derivatives: true
        }

    } );


    THREE.Mesh.call( this, geometry, material );

    this.frustumCulled = false;

};

THREE.InfiniteGridHelper.prototype = {
    ...THREE.Mesh.prototype,
    ...THREE.Object3D.prototype,
    ...THREE.EventDispatcher.prototype
};

if ( parseInt( THREE.REVISION ) > 126 ) {

    class InfiniteGridHelper extends THREE.Mesh {

        constructor ( size1, size2, color, distance, axes = 'xzy' ) {


            color = color || new THREE.Color( 'white' );
            size1 = size1 || 10;
            size2 = size2 || 100;

            distance = distance || 8000;



            const planeAxes = axes.substr( 0, 2 );

            const geometry = new THREE.PlaneBufferGeometry( 2, 2, 1, 1 );

            const material = new THREE.ShaderMaterial( {

                side: THREE.DoubleSide,

                uniforms: {
                    uSize1: {
                        value: size1
                    },
                    uSize2: {
                        value: size2
                    },
                    uColor: {
                        value: color
                    },
                    uDistance: {
                        value: distance
                    }
                },
                transparent: true,
                vertexShader: `
           
           varying vec3 worldPosition;
           
           uniform float uDistance;
           
           void main() {
           
                vec3 pos = position.${axes} * uDistance;
                pos.${planeAxes} += cameraPosition.${planeAxes};
                
                worldPosition = pos;
                
                gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
           
           }
           `,


                fragmentShader: `
           
           varying vec3 worldPosition;
           
           uniform float uSize1;
           uniform float uSize2;
           uniform vec3 uColor;
           uniform float uDistance;
            
            
            
            float getGrid(float size) {
            
                vec2 r = worldPosition.${planeAxes} / size;
                
                
                vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
                float line = min(grid.x, grid.y);
                
            
                return 1.0 - min(line, 1.0);
            }
            
           void main() {
           
                
                  float d = 1.0 - min(distance(cameraPosition.${planeAxes}, worldPosition.${planeAxes}) / uDistance, 1.0);
                
                  float g1 = getGrid(uSize1);
                  float g2 = getGrid(uSize2);
                  
                  
                  gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));
                  gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);
                
                  if ( gl_FragColor.a <= 0.0 ) discard;
                
           
           }
           
           `,

                extensions: {
                    derivatives: true
                }

            } );

            super( geometry, material );

            this.frustumCulled = false;

        }

    }
    
    Object.assign( InfiniteGridHelper.prototype, THREE.InfiniteGridHelper.prototype );

    THREE.InfiniteGridHelper = InfiniteGridHelper;

}


// creating the scene

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / 
    window.innerHeight, 0.1, 1000);
    camera.position.set(0,0,5);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

window.addEventListener('resize',function(){
    var width = window.innerWidth;
    var height = window.innerHeight;
    renderer.setSize(width, height);
    camera.aspect=window.innerWidth/ window.innerHeight;
    camera.updateProjectionMatrix();
})

const controls = new OrbitControls( camera, renderer.domElement );
controls.update()


// Infinite Grid Helper
const gridHelper = new THREE.InfiniteGridHelper(10, 100);
scene.add(gridHelper);
scene.add( gridHelper );

// Create a simple cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshNormalMaterial(); // MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

function animate() {
    requestAnimationFrame(animate);

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    renderer.render(scene, camera);
    controls.update()
}

animate();
<!DOCTYPE html>
<html>
<head>
    <title>Three.js Scene</title>
    <style>
        body { margin: 0; }
        canvas { width: 100%; height: 100% }
    </style>
</head>
<body>
        <script type="importmap"> { "imports": 
            { "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js", 
            "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"}} 
        </script>
        <script type="module" src="static/main.js"></script>

</body>
</html>