How do I add an external JS and use its function in my component in REACT?

I’ve been struggling on how to do this, I just want to import an external js and use it inside my function, however doing that gives a lot of errors whether React cant append child with async or the import failed to fetch dynamically.

Here’s my attempt

import {TAinit} from "https://my-assets.s3.ap-southeast-1.amazonaws.com/myjs.min.js";

export default function ClickToCall(){
function initializeC2C(hash) {
TAinit({
...
});
}

and here’s another:

export default async function ClickToCall(){
const myjs = await import(/* webpackIgnore: true */ "https://my-assets.s3.ap-southeast-1.amazonaws.com/myjs.min.js");
function initializeC2C(hash) {
myjs TAinit({
...
});
}

Side note: I cant enclose them in a function bec in my html return I’m calling a function connected to initializeC2C()

I dont know what Im doing wrong so anyone who can educate me I would appreciate it. I tried other searching and doing the answers too but doing those breaks my code.
Thanks!!!

Trouble with reading a noise texture in GLSL

I’m writing a Perlin noise terrain generator with p5js, following this tutorial. The app ran poorly so I decided to rewrite it with shaders, something i’ve never used before. I started by generating a subdivided plane of varying resolution to work with (I have no doubt there’s an easier way to do this):

const SCALE = 50;
function setup() {
    createCanvas(window.innerWidth, window.innerHeight, WEBGL);

    TERRAIN_W = width + floor(width / SCALE) * SCALE;
    TERRAIN_H = height + floor(height / SCALE) * SCALE;
    NUM_COLS = floor(TERRAIN_W / SCALE);
    NUM_ROWS = floor(TERRAIN_H / SCALE);

    plane_model = new p5.Geometry(NUM_COLS, NUM_ROWS, create_plane);
}

function create_plane() {
    let vert_map = []

    for (let y = 0; y < this.detailY; y++) {
        vert_map[y] = []
        for (let x = 0; x < this.detailX; x++) {
            this.vertices.push(createVector(x * SCALE, y * SCALE, 0));
            vert_map[y][x] = this.vertices.length - 1;

            this.uvs.push(x / (this.detailX - 1), y / (this.detailY - 1));
        }
    }

    for (let y = 0; y < this.detailY - 1; y++) {
        for (let x = 0; x < this.detailX - 1; x++) {
            let tl = vert_map[y][x];
            let tr = vert_map[y][x + 1];
            let bl = vert_map[y + 1][x];
            let br = vert_map[y + 1][x + 1];

            this.faces.push([tl, tr, bl]);
            this.faces.push([tr, br, bl]);
        }
    }
  
    this.computeNormals();
}

Then I created an image with the noise to pass to the vertex shader:


const NOISE_OFFSET = 0.05;
var fly_offset = 0;
function setup() {
    terrain_texture = createImage(NUM_ROWS, NUM_COLS);
}

function draw() {
    fly_offset += SHIFT_SPEED;
    let yoff = fly_offset;

    terrain_texture.loadPixels();
    for (let y = 0; y < NUM_ROWS; y++) {
        let xoff = 0;
        for (let x = 0; x < NUM_COLS; x++) {
            terrain_texture.set(x, y, color(map(noise(xoff, yoff), 0, 1, 0, 255)));
            xoff += NOISE_OFFSET;
        }
        yoff += NOISE_OFFSET;
    }
    terrain_texture.updatePixels();
    default_shader.setUniform("uTerrain", terrain_texture);
}

I create my vertex shader with a simple fragment shader that uses the texture coords for color:

#ifdef GL_ES
precision mediump float;
#endif

attribute vec3 aPosition;
attribute vec2 aTexCoord;

uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;

varying vec2 vTexCoord;

uniform sampler2D uTerrain;
uniform int uNumCols;
uniform int uNumRows;
uniform float uScale;

void main() {
    vec3 position = aPosition;

    vec2 uv = vec2(aPosition.x / float(uNumCols - 1), aPosition.y / float(uNumRows - 1));

    float height = texture2D(uTerrain, uv).r * 255.0;
    position.z += height;

    vec4 viewModelPosition = uModelViewMatrix * vec4(position, 1.0);

    gl_Position = uProjectionMatrix * viewModelPosition;
    vTexCoord = aTexCoord;
}

And finally load the shader, add the uniforms and use it to draw my plane:

function preload() {
    default_shader = loadShader("src/shader.vert", "src/shader.frag");
}

function setup() {
    default_shader.setUniform("uScale", SCALE);
    default_shader.setUniform("uNumCols", NUM_COLS);
    default_shader.setUniform("uNumRows", NUM_ROWS);
}

function draw() {
    default_shader.setUniform("uTerrain", terrain_texture);
    shader(default_shader);
    model(plane_model);
}

The end result is a flat plane that shifts up and down randomly.

1

My best guess is that I messed up the resolution of the terrain_texture or how I read the UVs in the vertex shader.
I have messed around with this a lot and could not reach a solution.

Desynchronized hover elements on touch devices

I’ve created a simple HTML that includes an image with a 3px white border around it and text below the image. Here is the HTML: https://jsbin.com/rofisiwoya/edit?html,output

When you hover over the image, the border around it turns red (#ff4444). However, since this represents a video, I wanted the border around the image and the text to turn red at the same time no matter which element you’re hovering over, pretty much linking the hover effect for both elements.

So, I did that using javascript. On my computer, you can hover over either element and it will activate the hover effect for both. There’s not really a way you could de-synchronize them. However, the hover effect works much differently on touch devices since you can’t really hover over them, you can only click things or press down to hold. So, I added this javascript for touch devices:

`
const ZodiacThumbnail = document.getElementById(‘zodiac-thumbnail’);
const ZodiacTitle = document.getElementById(‘zodiac-title’);

    function applyActiveState() {
        ZodiacTitle.classList.add('active');
        ZodiacThumbnail.querySelector('a').classList.add('active');
    }

    function removeActiveState() {
        ZodiacTitle.classList.remove('active');
        ZodiacThumbnail.querySelector('a').classList.remove('active');
    }

    ZodiacThumbnail.addEventListener('mouseover', applyActiveState);
    ZodiacThumbnail.addEventListener('mouseout', removeActiveState);
    ZodiacTitle.addEventListener('mouseover', applyActiveState);
    ZodiacTitle.addEventListener('mouseout', removeActiveState);

    ZodiacThumbnail.addEventListener('touchstart', applyActiveState);
    ZodiacTitle.addEventListener('touchstart', applyActiveState);

    document.addEventListener('touchend', function(event) {
        if (!ZodiacThumbnail.contains(event.target) && !ZodiacTitle.contains(event.target)) {
            removeActiveState();
        }
    });
</script>`

This made it so that if you held down on either element, it would activate the hover effect for both elements. Like I mentioned though, hover works differently on touch devices, and I quickly figured out that you could de-synchronize these elements by simply doing this: https://streamable.com/wtlzzv

Now, realistically, do I think somebody is going to sit on their mobile phone messing around with my website? Well, no. But it annoys me quite a bit, and if there’s something I can add into my javascript that prevents this I would love to do so, even if it involves redoing the way that I “linked” the hover effect. If it was just the image and no text, there wouldn’t be anything to synchronize, but the fact that you can actually de-synchronize it with little to no effort isn’t exactly beautiful especially since a lot of people visiting my website will likely be using their mobile device.

Selecting elements in HTML using tree generator extension

I have recently been trying to understand how to select elements and manipulate them using the html tree generator and JavaScript. How do I select the second last element of the last element child and also how do I select the links in order to manipulate them.

To select the second last element in the last element child I tried using : document.firstElementChild.lastElementChild.lastElementChild.lastElementChild…..but I still get a null hence cant change the element value.

Is it possible to execute a bat file from JavaScript running in modern browsers?

I have a question – is it possible to run a BAT file with JavaScript in a local HTML document?

My Batch file’s purpose is to sleep/hibernate the computer, and looks like this:
rundll32.exe powrprof.dll,SetSuspendState 0,1,0

I want to run it with JavaScript. I know it might be hard because of security reasons, but maybe running an HTA file executing that Batch file?

I tried creating an ActiveX object, but it doesn’t work in modern browsers.

Does anyone know the solution?

D3 Issue with custom link strength on update

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
  <style>
    svg {
      border: 1px black solid;
    }
  </style>
</head>

<body>
  <div>
    <div>
      <button id='btnRenderExisting2Node'>Render 2 existing nodes</button>
      <button id='btnRenderExisting3Node'>Render 3 existing nodes</button>
      <button id='btnRenderNewNode'>Render 3 existing nodes and 1 brand new node</button>
    </div>
    <svg width="250" height="250"></svg>
  </div>
  <script>
    var svg = d3.select("svg"),
      width = 250,
      height = 250,
      color = d3.scaleOrdinal(d3.schemeCategory10);

    var a = {
        id: "a"
      },
      b = {
        id: "b"
      },
      c = {
        id: "c"
      },
      nodes = [a, b, c],
      l_ab = {
        source: a,
        target: b
      },
      l_bc = {
        source: b,
        target: c
      },
      l_ca = {
        source: c,
        target: a
      },
      links = [l_ab, l_bc, l_ca];

    var id = 0;

    var simulation = d3.forceSimulation(nodes)
      .force('charge', d3.forceManyBody())
      .force('link', d3.forceLink().links(links).strength(d => {
        console.log(d);
        return 1;
      }))
      .force('center', d3.forceCenter(width / 2, height / 2))
      .alphaTarget(1)
      .on("tick", ticked)
      .stop();

    var g = svg.append("g"),
      link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
      node = g.append("g").attr("stroke", "#fff").attr("stroke-width", 1.5).selectAll(".node");

    function restart() {
      node = node.data(nodes);
      link = link.data(links);

      node.exit().transition().attr("r", 0).remove();
      link.exit().transition().attr("stroke-opacity", 0).remove();

      node = node.enter().append("circle")
        .attr("fill", d => color(d.id))
        .call(node => node.transition().attr("r", 8))
        .merge(node);

      link = link.enter().append("line")
        .call(link => link.transition().attr("stroke-opacity", 1))
        .merge(link);

      simulation.nodes(nodes);
      simulation.force("link").links(links)
        .strength(d => {
          console.log(d);
          return 1;
        });
      simulation.alpha(1).restart();
    }

    function ticked() {
      node.attr("cx", d => d.x)
        .attr("cy", d => d.y);

      link.attr("x1", d => d.source.x)
        .attr("y1", d => d.source.y)
        .attr("x2", d => d.target.x)
        .attr("y2", d => d.target.y);
    }

    restart();

    document.getElementById('btnRenderExisting3Node').addEventListener('click', function() {
      nodes = [a, b, c];
      links = [l_ab, l_bc, l_ca];
      restart();
    });

    document.getElementById('btnRenderExisting2Node').addEventListener('click', function() {
      nodes = [a, b];
      links = [l_ab];
      restart();
    });

    document.getElementById('btnRenderNewNode').addEventListener('click', function() {
      var d = {
        id: id++,
        x: width / 2,
        y: height / 2
      };
      nodes = [a, b, c, d];
      links = [l_ab, l_bc, l_ca, {
        source: a,
        target: d
      }];
      restart();
    });
  </script>
</body>

</html>

I need to refresh a d3 force graph with new data and also have a custom link strength, based on the properties of the edges.

This issue I run into happens when I use a custom link strength function and restart the simulation using the restart() function.

simulation.force("link").links(links)
    .strength(d => {
        console.log(d);
        return 1;
    });

The first time this runs, d will iterate over a different number of links and has unexpected behavior. Likewise, I find that if I try to redefine the strength function to return a different value, it keeps resorting to the original function.

Run 1

>>{source: {…}, target: {…}, index: 0}
>>{source: {…}, target: {…}, index: 1}
>>{source: {…}, target: {…}, index: 2}

Run 2

>>{source: {…}, target: {…}, index: 1}
>>{source: {…}, target: {…}, index: 2}
>>{source: {…}, target: {…}, index: 0}
>>{source: {…}, target: {…}, index: 1}
>>{source: {…}, target: {…}, index: 2}
>>{source: {…}, target: {…}, index: 3}
>>{source: {…}, target: {…}, index: 0}
>>{source: {…}, target: {…}, index: 1}
>>{source: {…}, target: {…}, index: 2}
>>{source: {…}, target: {…}, index: 3}

Run 3

>>{source: {…}, target: {…}, index: 0}
>>{source: {…}, target: {…}, index: 1}
>>{source: {…}, target: {…}, index: 2}
>>{source: {…}, target: {…}, index: 3}
>>{source: {…}, target: {…}, index: 0}
>>{source: {…}, target: {…}, index: 0}

It is seemingly unpredictable what it will output and sometimes uses data that isn’t from the current dataset. Why is this happening and is there anything I can do to mitigate the problem?

Full HTML Code:

<html>
<head>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
        svg {
            border: 1px black solid;
        }
    </style>
</head>
<body>
    <div>
        <div>
            <button id='btnRenderExisting2Node'>Render 2 existing nodes</button>
            <button id='btnRenderExisting3Node'>Render 3 existing nodes</button>
            <button id='btnRenderNewNode'>Render 3 existing nodes and 1 brand new node</button>
        </div>
        <svg width="250" height="250"></svg>
    </div>
    <script>
        var test = true;
        var svg = d3.select("svg"),
            width = 250,
            height = 250,
            color = d3.scaleOrdinal(d3.schemeCategory10);

        var a = {
                id: "a"
            },
            b = {
                id: "b"
            },
            c = {
                id: "c"
            },
            nodes = [a, b, c],
            l_ab = {
                source: a,
                target: b
            },
            l_bc = {
                source: b,
                target: c
            },
            l_ca = {
                source: c,
                target: a
            }
        links = [l_ab, l_bc, l_ca];

        var id = 0;

        var simulation = d3.forceSimulation(nodes)
            .force('charge', d3.forceManyBody())
            .force('link', d3.forceLink())
            .force('center', d3.forceCenter(width / 2, height / 2))
            .alphaTarget(1)
            .on("tick", ticked)
            .stop();

        var g = svg.append("g"),
            link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
            node = g.append("g").attr("stroke", "#fff").attr("stroke-width", 1.5).selectAll(".node");

        function restart() {

            // Updates the node & link data after nodes & links update
            node = node.data(nodes);
            link = link.data(links);

            console.log(node);
            console.log(link);

            // Select all nodes & links that need removal
            // after data update mismatch with DOM
            node.exit().transition()
                .attr("r", 0)
                .remove();

            link.exit().transition()
                .attr("stroke-opacity", 0)
                .attrTween("x1", d => {
                    return function () {
                        return d.source.x;
                    };
                })
                .attrTween("x2", d => {
                    return function () {
                        return d.target.x;
                    };
                })
                .attrTween("y1", d => {
                    return function () {
                        return d.source.y;
                    };
                })
                .attrTween("y2", d => {
                    return function () {
                        return d.target.y;
                    };
                })
                .remove();

            node = node.enter().append("circle")
                .attr("fill", d => color(d.id))
                .call(node => node.transition().attr("r", 8))
                .merge(node);

            link = link.enter().append("line")
                .call(link => link.transition().attr("stroke-opacity", 1))
                .merge(link);

            // Update and restart the simulation.
            simulation.nodes(nodes);
            simulation.force("link").links(links)
            .strength(d => {
                console.log(d);
                return 1;
            });
            simulation.alpha(1).restart();
        }

        function ticked() {
            node.attr("cx", d => d.x)
                .attr("cy", d => d.y);

            link.attr("x1", d => d.source.x)
                .attr("y1", d => d.source.y)
                .attr("x2", d => d.target.x)
                .attr("y2", d => d.target.y);
        }

        restart();

        document.getElementById('btnRenderExisting3Node').addEventListener('click', function () {
            nodes = [a, b, c];
            links = [l_ab, l_bc, l_ca];
            restart();
        });

        document.getElementById('btnRenderExisting2Node').addEventListener('click', function () {
            nodes = [a, b];
            links = [l_ab];
            restart();
        });

        document.getElementById('btnRenderNewNode').addEventListener('click', function () {
            var d = {
                id: id++,
                x: width / 2,
                y: height / 2
            };
            nodes = [a, b, c, d];
            links = [l_ab, l_bc, l_ca, {
                source: a,
                target: d
            }];
            restart();
        });
    </script>
</body>
</html>

How to Match Javascript id to my table view id

i could really use some help having trouble figuring out how to have the same id tag as what is in my view table below is my code where the ‘somethinghere’ is at is where i could use some help this needs to match the same value number as myRow for some reason it does not work. Any ideas?

<script src="~/Scripts/jquery-3.7.1.min.js"></script>

 <script type="text/javascript">

    $(document).ready(function () {
        var myRow = 0;
        $('.btnAddRecords').each(function () {
            myRow = myRow + 1;
            $(this).attr("id", "btnAddRecords" + myRow).click(function () {
                AddStudentRecords();
            })
        });
        $("#btnSaveData").click(function () {
            SaveStudentRecords();
        });
    });

    function AddStudentRecords() {
        var StudentRecords = "<tr><td>" + $("#txtSubject" + ***somethinghere***).val() + "</td><td>" +
                   $("#txtMarks" + ***somethinghere***).val() + "</td></tr>";
        $("#tableStudentRecords").last().append(StudentRecords);
    }

    function SaveStudentRecords() {
        var listOfStudentDetailModels = new Array();
        $("#tableStudentRecords").find("tr:gt(0)").each(function () {
            var Subject = $(this).find("td:eq(0)").text();
            var Marks = $(this).find("td:eq(1)").text();

            var Content = {}
            Content.Content_Name = Subject;
            Content.FieldID = Marks;
            listOfStudentDetailModels.push(Content);
        });

        $.ajax({
            async: true,
            type: "POST",
            dataType: "JSON",
            contentType: "application/json; charset=utf-8",
            url: "/Home/HomeView",
            data: JSON.stringify(listOfStudentDetailModels),
            success: function (data) {
                alert(data);
            },
        })
    }
   </script>

   <h2>Index</h2>

     <table>

    <tr>
        <td>
            Subject
        </td>
        <td>
            Marks
        </td>

    </tr>
    @{
        int i = 3;
        foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Content_Name)
                    @Html.HiddenFor(modelItem => item.Content_Name, new { id = "txtSubject" + i })
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ContentID)
                    @Html.HiddenFor(modelItem => item.ContentID, new { id = "txtMarks" + i })
                </td>
                <td>
                    <input class="btnAddRecords" type="button" id="btnAddRecords" value="Add" />

                </td>
            </tr>
            i += 1;
        }
    }
    </table>

    <table class="table-condensed" style="width: 100%" id="tableStudentRecords">
    <thread>
        <tr>
            <th>
                Subject
            </th>
            <th>
                Marks
            </th>
        </tr>
    </thread>
    </table>
    <input type="button" value="Save Data" name="SaveData" id="btnSaveData" class="btn btn-primary" />

if i replace somethinghere with hard coded values like 3 or 4 then it works for that but i need the values to each be unique so when i click on the add button it pulls the values that correspond to that particular row

JQuery Autocomplete function is triggering multiple times

I need to set a search bar in my code where it will retrive the data of the products present in the database.Here in the same project they have used the exact code to do the product search I used that in my page but the search function is activating and the list of items are given below the search box but when i try to click on the required product the success message is trigerring as much times of the product that i have filtered. For example milk is the product i have searched and i get four result to the that product search. When i click on one product the success in the autocomplete is called four times.And after clearing and again typing milk and try to click on a product the same four products apppear but this time the success method is called 8 times. I am little confused how to handle this. in the previous refrence also the same problem occurs but they have handle it with the if condition to avoid the multiple time calling the product appending function. I am in search of optimizing only calling the function one time. Can Anyone help me through it.

//html
<input type="text" class="form-control" id="search_product"  onkeyup="autocomplete_product();" placeholder="Product Code, Product Description">
//js
var autocomplete_product = function() { 
    var sort_by_product = "search_product";
    contactInvalid = true;

    if (contactInvalid == true) {
        $('#search_product').autocomplete($('#base_path').val() + "/CbManager/searchProducts/" + sort_by_product, {
            minChars: 1,
            cacheLength: false,
            autoFill: false,
            scrollHeight: 900,
            scroll: true,
        }).result(function(event, data, formatted) {
            var result = data.toString();
            if (result != "No Records.") {
                result = result.split(",");
                var len = result.length;
                if (product_id == 0) {
                    ajaxProductsId(result[len - 1]);
                }
            }
        });
    }
};
autocomplete_product();

This is the refrence code i am talking about.I have tryed to make many corrections using chatgpt and also referring the autocomplete documentation like using source method to get the result the source method itself not invoking
jQuery Autocomplete plugin 1.2.3 this is the version i am using to autocomplete

Saving an Apache Echart causes tainted canvas error

Saving the chart via the toolbox.feature.saveAsImage causes an error that says Tainted Canvas may not be exported. However, saving the image manually via right-clicking on the chart itself works just fine. I was wondering if there are any work-around on this? For deeper context, I’ve added images to the axis labels of the chart which may have caused it to become “tainted”

I’ve already tried using html2canvas together with the on render event handler of apache echart and it still doesn’t work. I’ve tried forwarding my port publicly and it also doesn’t work

How to update Cache in vscode.MarkdownString?

I am developing an extension and I am using an Image in MarkdownString that’s being cached by vscode

new vscode.MarkdownString(`<img src='${imgUri.path}'  width='200' height='200'/>`);

I have also tried creating images with different names and rendering, and it works prefectly.

But I don’t want to create multiple files, so I am updating existing image without creating a new Image, for this reason, imgUri Path remains same. The problem is that the image is not being updated when MarkdownString is being displayed.

I even tried cache busting using query params

new vscode.MarkdownString(`<img src='${imgUri.path}?time=${new Date().getTime()}' alt="rendered preview" />`);

but it still doesn’t update the markdown preview immediately. Is there a way to update the cache?

How to prevent tab changes in PrimeVue v3 TabView?

I am using PrimeVue V3 TabView with composition API.

Inside each tab I have a form and I want to trigger form validation before switching tabs. So I need to interrupt the tab change, do something (form validation), and then conditionally proceed to the clicked tab.

The TabView docs show 3 events: update:activeIndex, tab-change, and tab-click. But as far as I can tell, all of those are triggered after changing tabs, not before.

I found a similar question and answer based on the old Options API but I cannot get it working for Vue 3 Composition API.

Here is a live reproduction on stackblitz.

<template>
  <TabView
    v-model:activeIndex="activeIndex"
    @tab-change="handleTabChange"
    @tab-click="handleTabClick"
  >
    <TabPanel header="Opening Hours"> Opening hours form goes here </TabPanel>
    <TabPanel header="Contacts"> Contacts form goes here </TabPanel>
  </TabView>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import type { TabViewChangeEvent, TabViewClickEvent } from 'primevue/tabview';

const activeIndex = ref();

const handleTabClick = async (event: TabViewClickEvent) => {
  console.log('handleTabClick', event);
  const nextTabIndex = event.index;
  const isValid = false; // Simulated form validation
  if (isValid) {
    // Form is valid, continue with the tab change
    console.log('form valid');
    activeIndex.value = nextTabIndex;
  } else {
    // Form is invalid, do nothing (don't change tabs)
    console.log('form invalid');
  }
};

const handleTabChange = async (event: TabViewChangeEvent) => {
  console.log('handleTabChange', event);
  const nextTabIndex = event.index;
  const isValid = false; // Simulated form validation
  if (isValid) {
    // Form is valid, continue with the tab change
    console.log('form valid');
    activeIndex.value = nextTabIndex;
  } else {
    // Form is invalid, do nothing (don't change tabs)
    console.log('form invalid');
  }
};
</script>

Cannot convert undefined or null to object in shared-mixins.pug

I have btc-rpc-explorer running in Ubuntu. When I try to explore a selected Bitcoin block in the rpc explorer, I get the following error message:TypeError: /usr/local/lib/node_modules/btc-rpc-explorer/views/includes/shared-mixins.pug:227 227: if (!coinbaseTx && Object.keys(txInputs).length < tx.vin.length) Cannot convert undefined or null to object

Any suggestions on what is wring with the code in line 227??
Thanks

I have tried Googling for the answer but I’m not sure of the correct answer in my case, and I’m a noobie.

How do I replicate the exact animation done on flecto.io hero section

I came across https://flecto.io(use a vpn if the site doesn’t open) and the site caught my attention. I want to replicate the animation in the hero section. To be more precise, that is the part where the green rectangle turned into a cross-like shape.

Starting shape
enter image description here

Final Shape (I removed unwanted distractions)
enter image description here

I understand that this could be done with the use of gsap morphSVG plugin. But I am finding the use of that plugin for this purpose to be difficult. Here is a link to the demo I am working on Here.

HTML

<div class="container">
    <svg viewBox="0 0 1900 1500" fill="none">
      <g>
        <path id="rectangle" d="M0 0H1889V157V758V915H0V758V178.5V0Z" fill="black"/>
       
         <path id="final-stage" class="hide" d="M505.5 125.5H22.5H19C9.05887 125.5 1 133.559 1 143.5V774C1 783.941 9.05887 792 19 792H198.5C208.441 792 216.5 800.059 216.5 810V898C216.5 907.941 224.559 916 234.5 916H1426.5C1436.44 916 1444.5 907.941 1444.5 898V809.5C1444.5 799.559 1452.56 791.5 1462.5 791.5H1872C1881.94 791.5 1890 783.441 1890 773.5V144C1890 134.059 1881.94 126 1872 126H1385.5C1375.56 126 1367.5 117.941 1367.5 108V19C1367.5 9.05887 1359.44 1 1349.5 1H541.5C531.559 1 523.5 9.05888 523.5 19V107.5C523.5 117.441 515.441 125.5 505.5 125.5Z" fill="black" stroke="black" />
      </g>
    </svg>
  </div>

CSS

.container {
  width: 800px;
  height: 800px;
  display: flex;
  justify-content: center;
  align-items: center;
}
svg {
  width: 100%;
  height: 100%;
}

.hide {
  visibility: hidden;
}

Javascript (I am using gsap plugin, and gsap morphSVG plugin on codepen)

gsap.registerPlugin(MorphSVGPlugin);

// MorphSVGPlugin.defaultType = "rotational";

var tl = gsap.timeline();
const rectangle = document.getElementById("rectangle");

  tl.to(rectangle, { duration: 1, morphSVG: {shape: "#final-stage", shapeIndex: -2 }});

This was my result https://streamable.com/mnh46o (this content might not be available in the future)

The thing is that after inspecting the site, the creators didn’t morph a rectangle into a cross. They broke down their shape into smaller forms, consisting of two frames with different builds.

enter image description here

Notice that the first frame is a solid shape that has a cut out of a cross, while the second is a combination of several shapes that form the cut out of a cross. Why did they build the hero section this way? I am yet to figure it out. But I believe that this method is what makes their animation smoother than my method of morphing an SVG into a cross.

So, what do you all think? How can I replicate this design? What is the best method to do this?

multiple charts with amcharts 5

I’m developing a web application for a college project, in which I’m using the amcharts library to generate some graphs, however, I can only generate one graph in div’s with the id “chartdiv”, and this prevents me from generating more than one graph on the same page, does anyone have any idea what the error could be?

function createChart(id, data) {
    const root = am5.Root.new(id);
    root.setThemes([am5themes_Animated.new(root)]);

    const chart = root.container.children.push(am5percent.PieChart.new(root, {
        layout: root.verticalLayout
    }));

    const series = chart.series.push(am5percent.PieSeries.new(root, {
        valueField: "value",
        categoryField: "category"
    }));

    series.slices.template.setAll({
        fillOpacity: 1,
        stroke: am5.color(0x000000),
        strokeWidth: 1
    });

    series.get("colors").set("colors", [
        am5.color(0xa02a89),
        am5.color(0x6a1c71),
    ]);
    series.slices.template.set("toggleKey", "none");
    series.ticks.template.set("visible", false);
    series.labels.template.set("forceHidden", true);

    series.data.setAll(data);

    series.appear(1000, 100);
}


dataGraphic = [
            {value: "{{ vit }}", category: "Vitórias"}, 
            {value: "{{ qtd - vit }}", category: "Derrotas"}
        ];

am5.ready(createChart("chartdiv", dataGraphic));

I changed the id’s in the function call and it still didn’t work