Tooltip on “img” element containing an SVG doesn’t show up consistently

In JavaScript, I’m creating an image element that shows an SVG icon that includes transparent parts:

const iconImg = document.createElement("img");
iconImg.className = "host-icon";
iconImg.src = `img/host-icons/rehost.svg`;
iconImg.style.width = "24px";
iconImg.style.height = "24px";
iconImg.title = "My tooltip";

The icon (here PNG)

The problem is that the tooltip I set for it doesn’t always show up reliably. It seems that if I position the cursor in a transparent area of the icon, the furthest points between the border and the text, it doesn’t trigger the tooltip. Is this a known quirk with icons and tooltips? How can I solve this without giving the image a background? I’m using Firefox and also applying a color filter to the icon, if that is of importance.

Error using webcodecs to decode h264 data and display on browser from http fetch

I am getting :

(index):60 Error during fetch or decode process: DataError: Failed to execute ‘decode’ on ‘VideoDecoder’: A key frame is required after configure() or flush(). If you’re using AVC formatted H.264 you must fill out the description field in the VideoDecoderConfig.
at fetchAndDecodeJson ((index):55:24)”

when trying to decode the below h264 data in a json format via webcodec:

[
    {
        "type": "key",
        "pts": 0,
        "data": "Z0LgK28gAflBAQAAAwAAAPoAAIIAAO1BAQAAAwAAAPoAAOIwFA=="
    },
    {
        "type": "delta",
        "pts": 1,
        "data": "aMuHsyAABfsAAABAqAAABfsBAwABxAAAAgAAABfsBAwABxAAAgA=="
    },
    {
        "type": "delta",
        "pts": 2,
        "data": "aMuHsyAABfsAAABAqAAABfsBAwABxAAAAgAAABfsBAwABxAAAgA=="
    },
    {
        "type": "delta",
        "pts": 3,
        "data": "aMuHsyAABfsAAABAqAAABfsBAwABxAAAAgAAABfsBAwABxAAAgA=="
    }
]

My index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>decode H.264 to Canvas</title>
</head>
<body>
  <canvas id="output" style="border: 1px solid black;"></canvas>
  <script>
    async function fetchAndDecodeJson() {
      try {

        const response = await fetch("http://127.0.0.1:8000/datatest.json");
        const jsonData = await response.json();

        console.log("Fetched JSON Data:", jsonData);

        const canvas = document.getElementById("output");
        const ctx = canvas.getContext("2d");

        const videoDecoder = new VideoDecoder({
          output: (frame) => {
            canvas.width = frame.displayWidth;
            canvas.height = frame.displayHeight;
            ctx.drawImage(frame, 0, 0);
            frame.close();
          },
          error: (e) => console.error("decode error:", e),
        });

        const codecSupport = await VideoDecoder.isConfigSupported({
          codec: "avc1.42E01E",
        });

        if (!codecSupport.supported) {
          throw new Error("codec not supported");
        }

        videoDecoder.configure({ codec: "avc1.42E01E" });

        //decode each chunk from the JSON data
        for (const item of jsonData) {
          const { type, pts, data } = item;

          //base64 video data
          const rawData = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));

          //decode the video chunk
          const chunk = new EncodedVideoChunk({
            timestamp: pts * 1000, 
            type: type, 
            data: rawData,
          });

          videoDecoder.decode(chunk);
        }

        console.log("decode success");
      } catch (error) {
        console.error("decode or fetch error:", error);
      }
    }

    fetchAndDecodeJson().catch(console.error);
  </script>
</body>
</html>

the test frames are fetched but not decoded
enter image description here

i tried fiddling with sps and pps in the decoder config without success

Error using webcodecs to decode h264 data and display on browser from http fetch

I am getting :

(index):60 Error during fetch or decode process: DataError: Failed to execute ‘decode’ on ‘VideoDecoder’: A key frame is required after configure() or flush(). If you’re using AVC formatted H.264 you must fill out the description field in the VideoDecoderConfig.
at fetchAndDecodeJson ((index):55:24)”

when trying to decode the below h264 data in a json format via webcodec:

[
    {
        "type": "key",
        "pts": 0,
        "data": "Z0LgK28gAflBAQAAAwAAAPoAAIIAAO1BAQAAAwAAAPoAAOIwFA=="
    },
    {
        "type": "delta",
        "pts": 1,
        "data": "aMuHsyAABfsAAABAqAAABfsBAwABxAAAAgAAABfsBAwABxAAAgA=="
    },
    {
        "type": "delta",
        "pts": 2,
        "data": "aMuHsyAABfsAAABAqAAABfsBAwABxAAAAgAAABfsBAwABxAAAgA=="
    },
    {
        "type": "delta",
        "pts": 3,
        "data": "aMuHsyAABfsAAABAqAAABfsBAwABxAAAAgAAABfsBAwABxAAAgA=="
    }
]

My index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>decode H.264 to Canvas</title>
</head>
<body>
  <canvas id="output" style="border: 1px solid black;"></canvas>
  <script>
    async function fetchAndDecodeJson() {
      try {

        const response = await fetch("http://127.0.0.1:8000/datatest.json");
        const jsonData = await response.json();

        console.log("Fetched JSON Data:", jsonData);

        const canvas = document.getElementById("output");
        const ctx = canvas.getContext("2d");

        const videoDecoder = new VideoDecoder({
          output: (frame) => {
            canvas.width = frame.displayWidth;
            canvas.height = frame.displayHeight;
            ctx.drawImage(frame, 0, 0);
            frame.close();
          },
          error: (e) => console.error("decode error:", e),
        });

        const codecSupport = await VideoDecoder.isConfigSupported({
          codec: "avc1.42E01E",
        });

        if (!codecSupport.supported) {
          throw new Error("codec not supported");
        }

        videoDecoder.configure({ codec: "avc1.42E01E" });

        //decode each chunk from the JSON data
        for (const item of jsonData) {
          const { type, pts, data } = item;

          //base64 video data
          const rawData = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));

          //decode the video chunk
          const chunk = new EncodedVideoChunk({
            timestamp: pts * 1000, 
            type: type, 
            data: rawData,
          });

          videoDecoder.decode(chunk);
        }

        console.log("decode success");
      } catch (error) {
        console.error("decode or fetch error:", error);
      }
    }

    fetchAndDecodeJson().catch(console.error);
  </script>
</body>
</html>

the test frames are fetched but not decoded
enter image description here

i tried fiddling with sps and pps in the decoder config without success

display PDF form on the web, using react

I am currently trying to display a PDF form as part of my web page (not like described here: Embed a fillable pdf form on web page, they are using Acrobat for this). The user should be able to edit the PDF fields like he would in a PDF viewer. I’ve tried to use PDF.js for this, but I cannot find any good documentation on how to render the text and form part (See my question here: https://github.com/mozilla/pdf.js/discussions/19183). Also, the react-pdf module (https://www.npmjs.com/package/react-pdf) does not have any documentation for PDF forms. How do I achieve this?

The code I have came up with so far is (see link above, I am also using Mantine, but I do not think this is relevant for the question):

import { Button, Center, Flex, Input, Paper, Text } from "@mantine/core";
import * as pdfjslib from "pdfjs-dist";
import { useEffect, useRef, useState } from "react";
import { IconAt } from '@tabler/icons-react';
import $ from "jquery";

pdfjslib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.min.mjs',
    import.meta.url,
).toString();

async function renderCanvasLayer(pdfPage: pdfjslib.PDFPageProxy
    , canvas: HTMLCanvasElement
    , viewport: pdfjslib.PageViewport) {
    const ctx = canvas.getContext("2d")!;

    const renderTask = pdfPage.render({
        canvasContext: ctx,
        viewport,
    });

    return await renderTask.promise;
}


async function renderTextLayer(pdfPage: pdfjslib.PDFPageProxy
    , div: HTMLDivElement
    , canvas: HTMLCanvasElement
    , viewport: pdfjslib.PageViewport) {
    $(div.id)
        .css({
            left: canvas.offsetLeft + 'px',
            top: canvas.offsetTop + 'px',
            height: canvas.height + 'px',
            width: canvas.width + 'px'
        })
        .html("");

    const textLayer = new pdfjslib.TextLayer({
        textContentSource: await pdfPage.getTextContent(),
        container: div,
        viewport: viewport
    });

    return await textLayer.render();
}

async function renderXfaLayer(pdfPage: pdfjslib.PDFPageProxy) {
    //pdfjslib.XfaLayer.render({
    //    viewport: new PageViewport,
    //    div: undefined,
    //    xfaHtml: undefined,
    //    linkService: new IPDFLinkService
    //});
}

async function loadPDFPage(pdfDocument: pdfjslib.PDFDocumentProxy
    , canvas: HTMLCanvasElement
    , div: HTMLDivElement
    , pageNum: number) {
    const pdfPage: pdfjslib.PDFPageProxy = await pdfDocument.getPage(pageNum);

    const viewport = pdfPage.getViewport({
        scale: 1.5
    });

    canvas.width = viewport.width;
    canvas.height = viewport.height;

    await renderCanvasLayer(pdfPage, canvas, viewport);
    await renderTextLayer(pdfPage, div, canvas, viewport);
    await renderXfaLayer(pdfPage);
};

function Page({ numPage, pdfDocument }: { numPage: number, pdfDocument: pdfjslib.PDFDocumentProxy }) {
    console.assert(numPage != null);
    const pageCanvas = useRef<HTMLCanvasElement>(null);
    const pageDiv = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (pageCanvas.current && pageDiv.current) {
            loadPDFPage(pdfDocument, pageCanvas.current, pageDiv.current, numPage);
        }
    }, [pageCanvas]);

    return <>
        <Paper
            shadow="xl"
            p="xl">
            <Center>
                <Flex
                    mt={10}
                    mih={10}
                    gap="sm"
                    justify="center"
                    align="center"
                    direction="column"
                    wrap="wrap">

                    <canvas ref={pageCanvas}></canvas>

                    <div ref={pageDiv} className="select-text"></div>
                    <Text>Seite {numPage}</Text>
                </Flex>
            </Center>
        </Paper >
    </>
}

function PageArea({ numPages, pdfDocument }: { numPages: number, pdfDocument: pdfjslib.PDFDocumentProxy }) {
    const pages = [];

    for (let i = 1; i != numPages; i++) {
        pages.push(<Page numPage={i} pdfDocument={pdfDocument}></Page>);
    }

    return <>
        {pages}
    </>;
}

But I am also open for solutions using approaches other than PDF.js
Thanks!

display PDF form on the web, using react

I am currently trying to display a PDF form as part of my web page (not like described here: Embed a fillable pdf form on web page, they are using Acrobat for this). The user should be able to edit the PDF fields like he would in a PDF viewer. I’ve tried to use PDF.js for this, but I cannot find any good documentation on how to render the text and form part (See my question here: https://github.com/mozilla/pdf.js/discussions/19183). Also, the react-pdf module (https://www.npmjs.com/package/react-pdf) does not have any documentation for PDF forms. How do I achieve this?

The code I have came up with so far is (see link above, I am also using Mantine, but I do not think this is relevant for the question):

import { Button, Center, Flex, Input, Paper, Text } from "@mantine/core";
import * as pdfjslib from "pdfjs-dist";
import { useEffect, useRef, useState } from "react";
import { IconAt } from '@tabler/icons-react';
import $ from "jquery";

pdfjslib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.min.mjs',
    import.meta.url,
).toString();

async function renderCanvasLayer(pdfPage: pdfjslib.PDFPageProxy
    , canvas: HTMLCanvasElement
    , viewport: pdfjslib.PageViewport) {
    const ctx = canvas.getContext("2d")!;

    const renderTask = pdfPage.render({
        canvasContext: ctx,
        viewport,
    });

    return await renderTask.promise;
}


async function renderTextLayer(pdfPage: pdfjslib.PDFPageProxy
    , div: HTMLDivElement
    , canvas: HTMLCanvasElement
    , viewport: pdfjslib.PageViewport) {
    $(div.id)
        .css({
            left: canvas.offsetLeft + 'px',
            top: canvas.offsetTop + 'px',
            height: canvas.height + 'px',
            width: canvas.width + 'px'
        })
        .html("");

    const textLayer = new pdfjslib.TextLayer({
        textContentSource: await pdfPage.getTextContent(),
        container: div,
        viewport: viewport
    });

    return await textLayer.render();
}

async function renderXfaLayer(pdfPage: pdfjslib.PDFPageProxy) {
    //pdfjslib.XfaLayer.render({
    //    viewport: new PageViewport,
    //    div: undefined,
    //    xfaHtml: undefined,
    //    linkService: new IPDFLinkService
    //});
}

async function loadPDFPage(pdfDocument: pdfjslib.PDFDocumentProxy
    , canvas: HTMLCanvasElement
    , div: HTMLDivElement
    , pageNum: number) {
    const pdfPage: pdfjslib.PDFPageProxy = await pdfDocument.getPage(pageNum);

    const viewport = pdfPage.getViewport({
        scale: 1.5
    });

    canvas.width = viewport.width;
    canvas.height = viewport.height;

    await renderCanvasLayer(pdfPage, canvas, viewport);
    await renderTextLayer(pdfPage, div, canvas, viewport);
    await renderXfaLayer(pdfPage);
};

function Page({ numPage, pdfDocument }: { numPage: number, pdfDocument: pdfjslib.PDFDocumentProxy }) {
    console.assert(numPage != null);
    const pageCanvas = useRef<HTMLCanvasElement>(null);
    const pageDiv = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (pageCanvas.current && pageDiv.current) {
            loadPDFPage(pdfDocument, pageCanvas.current, pageDiv.current, numPage);
        }
    }, [pageCanvas]);

    return <>
        <Paper
            shadow="xl"
            p="xl">
            <Center>
                <Flex
                    mt={10}
                    mih={10}
                    gap="sm"
                    justify="center"
                    align="center"
                    direction="column"
                    wrap="wrap">

                    <canvas ref={pageCanvas}></canvas>

                    <div ref={pageDiv} className="select-text"></div>
                    <Text>Seite {numPage}</Text>
                </Flex>
            </Center>
        </Paper >
    </>
}

function PageArea({ numPages, pdfDocument }: { numPages: number, pdfDocument: pdfjslib.PDFDocumentProxy }) {
    const pages = [];

    for (let i = 1; i != numPages; i++) {
        pages.push(<Page numPage={i} pdfDocument={pdfDocument}></Page>);
    }

    return <>
        {pages}
    </>;
}

But I am also open for solutions using approaches other than PDF.js
Thanks!

When returning to an open tab in the navigator after some times, the app displays raw json instead of the page [closed]

I’ve noticed some strange behaviour with my Laravel/Inertia/vue.js app.

When returning to an open tab in the navigator after some time, the app displays raw JSON instead of the page. The JSON looks like the inertia response.

I’ve noticed this in Chrome but it might happen in other browsers.

This behaviour also sometimes happen when clicking the back button of the navigator.

Example of json displayed :

{
  "component": "Home",
  "props": {
    "jetstream": {
      "canCreateTeams": false,
      "canManageTwoFactorAuthentication": true,
      "canUpdatePassword": true,
      "canUpdateProfileInformation": true,
      "hasEmailVerification": false,
      "flash": [],
      "hasAccountDeletionFeatures": true,
      "hasApiFeatures": false,
      "hasTeamFeatures": false,
      "hasTermsAndPrivacyPolicyFeature": false,
      "managesProfilePhotos": false
    },
    "auth": {
      "user": {
        "id": 10,
        "name": "****",
        "first_name": "****",
        "last_name": "****",
        "registered_as": 1,
        "email": "****",
        "email_verified_at": null,
        "pre_registration_at": null,
        "two_factor_confirmed_at": null,
        "current_team_id": null,
        "profile_photo_path": null,
        "created_at": "2024-10-11T16:07:34.000000Z",
        "updated_at": "2024-10-11T16:12:43.000000Z",
        "profile_photo_url": "https://ui-avatars.com/api/?name=A+R&color=7F9CF5&background=EBF4FF",
        "two_factor_enabled": false
      }
    },
    "errorBags": [],
    "errors": {},
    "flash": {
      "toast": null
    },
    "categories": [
      "****"
    ],
    "filters": []
  },
  "url": "/",
  "version": "33fc74be0d1d546c3d41eede2b9ddfe3"
}

I’m unable to create a new project with React [closed]

I’m unable to create a new project with React. It created files but this error appears before ending.

npm install –no-audit –save @testinglibrary/jest-dom@^5.14.1@testing-liberary/react@^13.0.0 @testing-liberary/user-event@^13.2.1 web-vitals@^2.1.0′ failed

I used a lot of commands like:

npm install --save @testing-library/jest-dom@^5.14.1 @testing-library/react@^13.0.0 @testing-library/user-event@^13.2.1 web-vitals@^2.1.0

It finally couldn’t read package.json although it exists and is correct.

API recommendation: Display PDF as a react component including editable form fields [closed]

I am currently trying to display a PDF form as part of my web page. The user should be able to edit the PDF fields like he would in a PDF viewer. I’ve tried to use PDF.js for this, but I cannot find any good documentation on how to render the text and form part (See my question here: https://github.com/mozilla/pdf.js/discussions/19183). Are there any frameworks/modules that allow thi? I have tried the react-pdf module, but I have not managed to get the form layer working.

Thanks!

unable to create anew project with React

unable to create a new project with React ..it created files but this error appears before ending
the error: ‘npm install –no-audit –save @testinglibrary/jest-dom@^5.14.1@testing-liberary/react@^13.0.0 @testing-liberary/user-event@^13.2.1 web-vitals@^2.1.0’ failed

used a lot of commands like
npm install –save @testing-library/jest-dom@^5.14.1 @testing-library/react@^13.0.0 @testing-library/user-event@^13.2.1 web-vitals@^2.1.0

but finally couldn’t read package.json although it already found and correct

How to connect a React frontend with a Node.js backend and MySQL database? [closed]

I’m building a full-stack application and need to connect my React frontend to a Node.js backend that interacts with a MySQL database. Here’s what I want to achieve:

  1. Fetch data from a MySQL database and display it in a React component.
  2. Use a Node.js server as the API layer to handle database queries.
  3. Make HTTP requests from React to the Node.js server to get the data.

I’ve already set up a basic React app and installed express and MySQL in my Node.js project, but I’m not sure how to structure the code for the connection between these components. Could someone provide a simple example or best practices for achieving this?

Merge two object and combine values with similar keys as array

I have 2 object with similar key in each objects whose value is array of string.

const obj1 = {
“page”: “test”,
“id”: “alpha”,
“custom_variable”: [
“joe”
],
“custom_format”: [
“jack”
]
}

const obj2 = {
“product”: “random”,
“id”: “beta”,
“custom_variable”: [
“kate”
],
“custom_format”: [
“gamma”
]
}

Now, i am expecting result to be like:

finalObj = {
“page”: “test”,
“id”: “alpha”,
“product”: “random”,
“productid”: “beta”,
“custom_variable”: [“joe”, “kate”], // merge those values
“custom_format”: [“jack”, “gamma”] // merge those values
}

Hide Form Action in Source code or web developer

i have ilias lms website on our server but we want to hide the form action name in source code and web developer, is there any solution on this matter. it html file.

<form id="form_" role="form" class="form-horizontal preventDoubleSubmission" name="formlogin" action="ilias.php?lang=en&amp;client_id=renv1&amp;cmd=post&amp;cmdClass=ilstartupgui&amp;cmdNode=xv&amp;baseClass=ilStartUpGUI&amp;rtoken=" method="post" novalidate="novalidate">

Google Apps Script Data Manipulation to SpreadSheet Asynchronously

We are trying to handle (to import data via Plaid API), large amount of data on the spreadsheet (google sheet). The external API needs to be used in the while loop because response needs to be check the condition is true or false. If the conditions meets true then the loop will continue until condition false. And also the external API has limit restrictions(50 calls per minute). We need to store all the response in a single variable like array collection then we need to format and manipulate them in the spreadsheets.

We have shared the code here for you.

Following approach: https://gist.github.com/sdesalas/2972f8647897d5481fd8e01f03122805

Async.call('updateSpreadSheet');

var responseData = [];

function updateSpreadSheet(){
  var collection = [];
  let response = fetchAPITransactions();
  if( response == true ){
   collection = fetchMoreAPITransactions();
  }
  if(collection.length > 0 ){
   manipulateDatatToSpreadsheet(collection);
  }
}

function manipulateDatatToSpreadsheet(){
 //format data and add/remove data on the spreadsheets.
}

function fetchMoreAPITransactions( response ){
 while( response == true ){
    responseData.push( response);
  break;
  }
  return responseData;
}
 
function fetchAPITransactions(){
 //call api end point and response. 50 calls per minute. 
 var response = responsedataofAPI;
 return response;
}

Is this approach correct for calling the Async function to execute the loop, the triggers are not called sequentially, this makes the data in the Spreadsheet also not in correct format. or not in sequence as per date order. This process also runs for a very long time 45 to 60 minutes which is not practically feasible while retrieving the data. What is the best approach in this case? We expect the data to be ordered by date in the spreadsheet and to fetch the data much quicker.

Thanks in Advance.

Three.js project: Uncaught TypeError: Failed to resolve module specifier “three”. Relative references must start with either “/”, “./”, or “../”

I’m attempting to use cdn to import the three library as well as several add ons and N8AO. As stated in the title I’m encountering the listed error:

Uncaught TypeError: Failed to resolve module specifier “three”. Relative references must start with either “/”, “./”, or “../”..

I’m getting the error in Chrome however I have not tried any other browser yet. I’m also using WebStorm as my development environment.
I have node.js version 22.12.0 installed however I am just scripting the entirety of the functionality in the html file rather than creating a separate javascript file for the sake of having everything in one spot.
I presume it’s coming from one of the import statements given here. Also including the rest of the project as it may provide other insights:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Three.js Terrain with Grass and N8AO</title>
  <style>
    body { margin: 0; overflow: hidden; }
    canvas { display: block; }
  </style>
</head>
<body>
<script type="module">
  import * as THREE from 'https://unpkg.com/[email protected]/build/three.module.js';
  import { OrbitControls } from 'https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls.js';
  import { EffectComposer } from 'https://unpkg.com/[email protected]/examples/jsm/postprocessing/EffectComposer.js';
  import { N8AOPass } from "https://unpkg.com/n8ao@latest/dist/N8AO.js";

  // Scene, Camera, Renderer
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.set(15, 15, 10);

  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  document.body.appendChild(renderer.domElement);

  // Controls
  const controls = new OrbitControls(camera, renderer.domElement);
  controls.minPolarAngle = Math.PI / 2.5;
  controls.maxPolarAngle = Math.PI / 2.5;

  // Sky and lighting
  scene.background = new THREE.Color(0xaabbff); // Sky color
  scene.add(new THREE.AmbientLight(0x404040)); // Soft ambient light

  const pointLight = new THREE.PointLight(0xffffff, 1);
  pointLight.position.set(10, 10, 10);
  pointLight.castShadow = true;
  scene.add(pointLight);

  // Terrain
  const width = 100;
  const terrainGeometry = new THREE.PlaneGeometry(width, width, 64, 64);
  terrainGeometry.rotateX(-Math.PI / 2);

  // Generate elevation for terrain
  const simplex = new THREE.SimplexNoise();
  for (let i = 0; i < terrainGeometry.attributes.position.count; i++) {
    const x = terrainGeometry.attributes.position.array[i * 3];
    const z = terrainGeometry.attributes.position.array[i * 3 + 2];
    const y = 2 * simplex.noise2D(x / 10, z / 10) + 3 * simplex.noise2D(x / 15, z / 15);
    terrainGeometry.attributes.position.array[i * 3 + 1] = y;
  }
  terrainGeometry.computeVertexNormals();

  const terrainMaterial = new THREE.MeshStandardMaterial({ color: 0x228b22 });
  const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
  terrain.receiveShadow = true;
  scene.add(terrain);

  // Grass
  const grassGroup = new THREE.Group();
  const bladeGeometry = new THREE.PlaneGeometry(0.12, 1, 1, 4).translate(0, 0.5, 0);
  const grassMaterial = new THREE.MeshStandardMaterial({ color: 0x32cd32, side: THREE.DoubleSide });

  for (let i = 0; i < 50000; i++) {
    const blade = new THREE.Mesh(bladeGeometry, grassMaterial);
    blade.position.set(
            Math.random() * width - width / 2,
            0,
            Math.random() * width - width / 2
    );
    blade.rotation.y = Math.random() * Math.PI * 2;
    blade.scale.y = 0.5 + Math.random() * 0.5;
    grassGroup.add(blade);
  }
  scene.add(grassGroup);

  // Post-Processing with N8AOPass
  const composer = new EffectComposer(renderer);
  const n8aoPass = new N8AOPass(scene, camera, window.innerWidth, window.innerHeight);
  composer.addPass(n8aoPass);

  // Adjust N8AOPass Parameters
  n8aoPass.configuration.aoRadius = 5.0; // Set AO radius
  n8aoPass.configuration.distanceFalloff = 1.0; // Distance attenuation
  n8aoPass.configuration.intensity = 3.0; // AO intensity
  n8aoPass.configuration.color = new THREE.Color(0, 0, 0); // AO color
  n8aoPass.configuration.halfRes = false; // Full resolution for better quality

  // Animation loop
  function animate() {
    requestAnimationFrame(animate);

    // Simulate grass swaying in the wind
    grassGroup.children.forEach((blade) => {
      blade.rotation.x = 0.1 * Math.sin(performance.now() / 1000 + blade.position.x);
    });

    composer.render();
  }
  animate();

  // Handle resizing
  window.addEventListener("resize", () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    composer.setSize(window.innerWidth, window.innerHeight);
  });
</script>
</body>
</html>

The version of Chrome I am using is 131.0.6778.109
The version of Webstorm I’m using is #WS-242.21829.149

catch on a Promise

I am new to Javascript and trying to understand how Promise really works. I understand basics of how chaining works in Promise.

Is version 1 equivalent to version 2.

How does version 2 works? Since “catch” is chained to “then”, does “then” returns a “Promise”?

version 1:

const pr = new Promise((resolve, reject) => {
  const test = false;

  if (test) {
    resolve("Promise resolved");
  } else {
    reject("Promise Rejected");
  }
});

pr.then((resolve) => console.log(resolve));

pr.catch((error) => console.log(error));

version 2:

const pr = new Promise((resolve, reject) => {
  const test = false;

  if (test) {
    resolve("Promise resolved");
  } else {
    reject("Promise Rejected");
  }
});

pr.then((resolve) => console.log(resolve))
.catch((error) => console.log(error));