How to create a fractal background similar to this one using JavaScript and WebGL/Canvas?

I’m trying to create a fractal background similar to the one shown in the image (link below). It has an interesting structure, resembling branching fractals with smooth color transitions. I’ve searched online and even consulted ChatGPT, but I haven’t found a clear understanding of how to achieve such an effect.

Link to the image I’m aiming for

enter image description here

Questions:
Is it possible to create such a background using JavaScript, WebGL, or Canvas?
What algorithms or techniques can be used to generate similar fractals? For example, would fractal tree algorithms, Perlin noise, or something else be appropriate?
Is WebGL a good choice for creating this effect? If so, what are the key steps or tools to use?
Is it possible to achieve a similar effect using Canvas, or would it be better to focus on WebGL for better performance?
I’ve tried using Canvas to generate random fractals, and I’ve also explored working with WebGL. However, I encountered difficulties when trying to create complex and detailed structures like the one in the image.

My Expectations:

I’d like the background to have random variations, resembling branches, but still remain smooth and not overload the browser.
I am interested in whether there are existing libraries or examples that could help me.
I would greatly appreciate any advice or directions that could help me implement this effect. Links to code, articles, or tutorials on similar topics would be especially useful.

Thank you for your help!

AJAX Posts Reverse Order After Refresh the Page When Multiple Posts are Created in the Same Minute from Same User

I’m working on a social network project using Django for the backend and JavaScript for the frontend. Users can post new content, and the global feed is updated both dynamically via Ajax and by refreshing the page.

Everything works fine, except when a user creates multiple posts within the same minute. Initially, the newest post is displayed at the top, but when I refresh the page, the order of posts gets reversed for that specific user, where older posts appear above newer ones.

I’m using the created_at field (with DateTimeField) to order the posts. Here’s a snippet of the key code that handles fetching the global stream and updating the DOM:

function updateStream(posts) {
    const postContainer = document.querySelector('#post-list');

    posts.forEach(post => {
        let postElement = document.getElementById(`id_post_div_${post.post_id}`);

        if (!postElement) {
            postElement = document.createElement('div');
            postElement.id = `id_post_div_${post.post_id}`;
            postElement.className = 'post';
            postElement.innerHTML = `
                <p>
                    <strong><a href="/profile/${post.author_username}" id="id_post_profile_${post.post_id}" class="post-profile">
                        ${post.author}</a></strong>: 
                    <span id="id_post_text_${post.post_id}" class="post-txt">${sanitize(post.content)}</span>
                    <span id="id_post_date_time_${post.post_id}" class="post-date-time">${formatDate(post.created_at)}</span>
                </p>
                <div class="comments" id="comments_${post.post_id}"></div>
                <div id="id_comment_input_div_${post.post_id}" class="add-comment">
                    <input type="text" id="id_comment_input_text_${post.post_id}" placeholder="Add a comment" />
                    <button id="id_comment_button_${post.post_id}" onclick="addComment(${post.post_id})">Submit</button>
                </div>
            `;

            // Add new post to the correct position
            postContainer.appendChild(postElement);
        }
    });
}

What I’ve Tried:

Adding a fallback to sort by post_id when posts have the same created_at, but it didn’t seem to fix the issue completely.
My Question: How can I ensure that new posts are always displayed at the top, even when multiple posts are created within the same minute?

Any suggestions or guidance on the proper way to handle this would be greatly appreciated!

Get element(s) text the synchronous way with Cypress

I have a multiselect dropdown on a page. This dropdown can have 0 or more selected values. Here is the function that reads those values and returns an array:

async readSelected(){
  const result = [];
  await cy.xpath("//*[@blabla='bla']//li").each(e => result.push(e.text()));
  return result;
}

It works for cases when 1 or more elements is found, but for 0 it throws an exception, which is not what I want. Instead, the result must be just an empty array.

How to make it work?

P.S.
As the title may suggest, handling such cases with then(), should() and other Cypress chained methods when values must be processed from within callback functions with no option to explicitly await it and get the actual values instead of promise of promise-like object is not the solution I’m looking for

Trying to trigger an event once progress bar animation is compete

I’m successfully using the below HTML code to trigger a completion event in our LMS.


<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Post-Survey: Workplace</title>
  <script>
    window.addEventListener('message', e => window.evolve = e.ports[0]);
</script>
</head>

<body class="htmlNoPages">
<center><iframe src="https://docs.google.com/forms/..." onLoad="evolve?.postMessage('completed')" style="border:none;" height="1000" width="800"/></center>
</body>

</html>

We are trying to create the same trigger using a progress bar that launches on page load and have found the below code sample to help get started, but I can’t figure out how to get the bar’s end to trigger in the same. Can anyone help?

<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<div class="w3-container">

  <div class="w3-light-grey">
    <div id="myBar" class="w3-container w3-green" style="height:24px;width:0%">
    </div>
  </div>

  <p id="myP">Added <span id="demo">0</span> of 10 photos</p>

<body onload="move()">
</div>

<script>

function move() {
  var elem = document.getElementById("myBar");   
  var width = 0;
  var id = setInterval(frame, 50);
  function frame() {
    if (width >= 100) {
      clearInterval(id);
      document.getElementById("myP").className = "w3-text-green w3-animate-opacity";
      document.getElementById("myP").innerHTML = "Successfully uploaded 10 photos!";
      window.addEventListener('message', e => window.evolve = e.ports[0]);
      document.addEventListener("load", "evolve?.postMessage('completed')")


    }
  }
}
</script>

</body>
</html>

I’ve tried a few iterations of combining these codes, but none have worked.

Ideally, removing any of the text about uploading photos, we would just have a progress bar that starts on page load and when finishing loading, executes the same outcome as the iframe code.

Pixel height size of an A4 sheet of paper when printing from chrome

I have a print page that contains different modules that can be different lengths. When I try to print, I would like the next module to be on a separate page if it is greater than 2/3 down the page. In order to do this I use element.getBoundingClientRect(), which I think is in pixels. I need to know the page(A4) height so I can determine where on the individual page the element currently is. Does anyone know these numbers or how I can calculate them?

Getting Exact Offset when using Accordian jQuery

I have created an accordian on my webpage that dropdowns the answers(A) of questions(Q), If a user clicks Q1 the A1 div scrolls down to open up and if a users clicks Q2, A1 div slides up to hide and A2 div slides down to show up. I have setup jquery to keep the clicked/active question(Q) on top of the screen that’s the main part which I setup using jQuery.

The issue I am having is when a user clicks the Q1 and scrolls down without closing it to Q2 and clicks it the A1 div first closes down and then the A2 div opens up in the meantime the Q2 which is supposed to scroll up on top of the page move further up because the A1 div closes and the offset I am getting is not accurate. I am using the code below to keep the Question div clicked on top of the page. How can I get the accurate offset when a user clicks Questions without closing them? Please note the height of the Answer divs is different depending on the content.

jQuery(document).ready(function($) {

    $('.e-n-accordion-item').on('click', function() {
        
                     var offset = $(this).offset();
        
        var scrollTop = $(window).scrollTop();
        
        var topRelativeToScroll = offset.top - scrollTop;
        
        var scrollToPosition = $(window).scrollTop() + topRelativeToScroll - 100;
        
    console.log(scrollToPosition);
    
        $('html, body').animate({ scrollTop: scrollToPosition }, 1); 
                    
    });
});

Page Load Runs Twice When HREF Attribute Set to “#” in Link Tag

I’m experiencing something weird, that I need help understanding. When I use a link tag with the “href” attribute set to “#”, it causes the Page Load event to run twice.

For example, in the following link tag, I’m using “#” as the value for the “href” attribute. I’m using this in place of using a real “shorcut icon” and only to avoid the javascript warning/error. So, I could simply remove it, but I’d like to understand what is goin on (or how to fix it, without removing it):

<link rel="shortcut icon" href="#">

Sample HTML:

<!doctype html>
<html lang="en">
<head runat="server">
    <title>My Example</title>
    <!-- The "href=#" in the following link tag triggers the 'Page load' event to run twice. -->
    <link rel="shortcut icon" href="#">
</head>
<body>
    <form id="form1" runat="server">
        <h1>My Example</h1>
    </form>
</body>
</html>

Sample VB.NET Code Behind Page:

Partial Class myexample
    Inherits System.Web.UI.Page

    Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        'This is triggered twice.
    End Sub
End Class

This also happens with using it for “stylesheet” link tags as shown below:

<link rel="stylesheet" href="#" />  

JavaScript – Flatten nested JSON object [duplicate]

How could I turn this

{
  "root": {
    "sub": 1,
    "sub2": 2,
  },
  "root2": 3
}

into this

{
  "root.sub": 1,
  "root.sub2": 2,
  "root2": 3
}

though a function programmatically?

I have literally no idea how I would do it, but I’ve tried to create a function which uses a cursor/pointer to jump through all child objects, but could not find a way to repeat the process.

THREE.js PointLight Not Working w/ Phong Material

I’ve updated some of my old code to use the new 3JS release and have got everything working except the PointLight with the PhongMaterial. The attached code creates a cube with a phong mesh that’s blue in color but emits green and without any lighting it appears as a green blob like expected. When I add a white ambient light the cube color looks more cyan also expected. Then I add a red point light right in between the camera and the cube and I expect the color to change and to see the geometry but it’s still the same colored blob I get with the ambient light. How do I get this point light to work?

<!DOCTYPE html>

<html>

    <head>
        <title>3js Light Test</title>       
    </head>

    <body>
        <div id="webgl-container"></div>

        <script type="importmap">
            {
                "imports": {
                    "three": "https://threejs.org/build/three.module.js",
                    "three/addons/": "https://threejs.org/examples/jsm/"
                }
            }
        </script>
        
        <script type="module" src="static/light.js"></script>
    </body>

</html>

import * as THREE from "three"

"use strict";

const scene    = new THREE.Scene();
const renderer = new THREE.WebGLRenderer();
const camera   = new THREE.PerspectiveCamera(40,                                     // Field of View
                                             window.innerWidth / window.innerHeight, // Aspect Ratio
                                             .1,                                     // Near Clipping Plane
                                             1000)                                   // Far Clipping Plane

var cube;

function initScene(){
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.getElementById("webgl-container").appendChild(renderer.domElement);

    const phong_material = new THREE.MeshPhongMaterial({ color: 0x0000ff, wireframe: false, emissive: 0x00ff00, reflectivity: 10, shininess: 100 }); // Blue Phong Material
    var geometry = new THREE.BoxGeometry(10, 10, 10)
    cube = new THREE.Mesh(geometry, phong_material)
    scene.add(cube)

    const ambient_light  = new THREE.AmbientLight(0xffffff); // White ambient light
    scene.add(ambient_light);

    const point_light    = new THREE.PointLight({ color: 0xff0000, intesity: 5000 } ); // Red point light
    point_light.position.set(0, 0, 50);
    scene.add(point_light);

    camera.position.z= 100;
    scene.add( camera );

    render();
}

// Recursively draw scene
function render(){
    cube.rotation.y +=0.01;
    cube.rotation.x += 0.005;

    renderer.render(scene, camera); 
    requestAnimationFrame(render);
}

window.onload = initScene;

Page jumps after hiding content

How can the jumping be prevented?
Here is a video of the issue: https://streamable.com/t2cyu3

I have a grid with many grid items.
This grid can be expanded or collapsed to show/hide its content.
The expand/collapse is being done by adding and removing a class named “expanded” in javascript.

The expand/collapse happens when you press the “toggle” button.

If you scroll below the last grid item (the blue boxes), press the toggle button, and then press the toggle button a second time, the page will jump to the bottom of the page.

const toggleButton = document.getElementById("toggle-button")

const grid = document.getElementById("grid")

let isExpanded = true

toggleButton.addEventListener("click", () => {
  isExpanded = !isExpanded

  if (isExpanded) {
    grid.classList.add("expanded")
  } else {
    grid.classList.remove("expanded")
  }
})
body {
  padding: 72px;
}

.filler-content {
  background: seashell;
  width: 100%;
  height: 1600px;
}

#grid {
  background: black;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.grid-item {
  background: blue;
  padding: 80px;
}

#toggle-button {
  background: orange;
  padding: 16px;
  position: fixed;
  bottom: 4px;
}

.expanded {
  max-height: 20rem;
  overflow: hidden;
}
<div class="filler-content">filler content... scroll down</div>

<section>
  <p>this is the grid with grid items</p>
  <div id="grid" class="expanded">
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
  </div>

  <div id="toggle-button">Toggle</div>
</section>

<div class="filler-content">filler content.. press the toggle button when this text is above the button</div>

I can’t seem to get Navigation to work in Rizz UI tab component

I used the tab component by Rizz UI to build navigation and now I want to make the tabs navigate from one page to another based on id value. I am using next.js.

<div className={`w-full flex flex-col`}>
        <Tab >
            <Tab.List >
            {
                patientNavigationData?.map((item, index)=>(
                    
               <Tab.ListItem  key={item?.id}>
                 {item?.icon} {item?.navName}
                </Tab.ListItem>))}
        </Tab.List>
         </Tab>

How can I add the Next.js Link component here? I have checked their documentation, didn’t see anything mentioned regarding this.

iPhone Automatically Converting HEIC/HEVC Files When Using — How to Prevent This?

I’m working on a web app that allows users to upload images and videos using an <input type="file"> html element. However, when iPhone users select files from the Photo Library, iOS automatically converts HEIC images to JPEG and HEVC videos to MP4. This conversion results in slower file selection and adds unnecessary overhead, and the user is “stuck” on the Photo Library selection pop-up until iOS finishes converting everything to a more “compatible format”.

I’ve tried removing the accept attribute entirely, hoping it would prevent the conversion, but the issue persists. I would like to find a way to accept the iPhone’s native formats (HEIC/HEVC) without having iOS automatically convert them. I want users to be able to upload their files without the device forcing format changes.

What I’ve Tried:

Using an empty accept attribute: Removing the accept attribute works for preventing restrictions on file types, but the iPhone still converts HEIC/HEVC files when selecting from the Photo Library.
Setting accept=”image/heic, video/hevc”: I tried explicitly accepting these formats, but Safari/iOS continues to convert files.
Filtering files after selection: I attempted to filter files client-side, but the iPhone still transforms them before selection.

What I Want: I want iPhones to stop converting HEIC and HEVC files and upload them in their original format. I prefer to handle any necessary conversion on the server side.

Question:

Is there a way to tell iOS not to automatically convert files in the selection process?
Can the file input’s accept attribute (or any other approach) prevent this automatic conversion?
Are there any workarounds, or do I have to rely on just telling the user before hand that it will take a while for the Photo Library Pop-up to disappear as iOS is running some conversions.

NOTE: On iOS I can configure the Photo Library selection format from “Automatic” (which performs the conversion) to “Current”. That works and forces iOS not to perform any conversions, however it requires the user to do some extra configuration steps on the website – which I am also trying to avoid if possible.

Environment:

Devices: iPhones (iOS 14+)
Browsers: Safari on iOS
Formats: HEIC (images), HEVC (videos)

Any help or suggestions would be greatly appreciated!

Why is currentTranscription empty after being set in my React component?

I’m building a React component that streams audio and transcribes it in real-time using a WebSocket connection. I have a state variable currentTranscription that should accumulate the transcriptions as they come in. However, I am encountering an issue where currentTranscription is empty when I try to call setTranscription, when data.speech_final is true, even tho i see its content in the UI.

I guess it’s something related to the asynchronous behaviour of the setState but I can’t figure it out what’s the issue.

Here’s a simplified version of my code:

import { useState, useEffect, useRef } from 'react';

function Interview() {
  const [currentTranscription, setCurrentTranscription] = useState('');
  const [transcriptions, setTranscriptions] = useState<string[]>([]);

  const socket = useRef<WebSocket | null>(null);

  useEffect(() => {
    socket.current = new WebSocket('ws://localhost:3000');

    socket.current.addEventListener('message', (event) => {
      const data = JSON.parse(event.data);
      if (data.channel && data.channel.alternatives) {
        const transcript = data.channel.alternatives[0].transcript;

        if (transcript && data.is_final) {
          setCurrentTranscription((prevTranscription) => prevTranscription + ' ' + transcript);
        }

        if (data.speech_final) {
        // currentTranscription is empty
          setTranscriptions((prevTranscriptions) => [...prevTranscriptions, currentTranscription]);
          setCurrentTranscription('');
        }
      }
    });

    return () => {
      socket.current?.close();
    };
  }, []);

  return <div>{currentTranscription}</div>;
}

How to auto scroll vertically and also horizontally toward the mouse pointer?

I am using react-bubble-ui this package.

import BubbleUI from "react-bubble-ui";
import "react-bubble-ui/dist/index.css";
import Child from "./ChildComponent";
import "./bees_bubble.css";

export default function Bubbles({ bees }) {
  const options = {
    size: 65,
    minSize: 20,
    gutter: 10,
    provideProps: true,
    numCols: 25,
    fringeWidth: 10,
    fringeHeight: 10,
    yRadius: 100,
    xRadius: 100,
    cornerRadius: 50,
    showGuides: false,
    compact: true,
    gravitation: 5,
  };

  const children = bees?.map((data: any, i: number) => {
    return <Child data={data} key={i} />;
  });

  return (
    <BubbleUI options={options} className="h-[300px] rounded-50">
      {children}
    </BubbleUI>
  );
}

I achieved the desired look. But the problem is that I can’t move horizontally. Mouse wheel only scrolls to vertical direction. I want to scroll it to where the mouse pointer is. I could not isolate the affect only to this component.

import { useState, useEffect, useRef } from "react";
import BubbleUI from "react-bubble-ui";
import "react-bubble-ui/dist/index.css";
import Child from "./ChildComponent";
import "./bees_bubble.css";

export default function Bubbles({ bees }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const bubbleContainerRef = useRef<HTMLDivElement>(null);

  const options = {
    size: 65,
    minSize: 20,
    gutter: 10,
    provideProps: true,
    numCols: 25,
    fringeWidth: 10,
    fringeHeight: 10,
    yRadius: 100,
    xRadius: 100,
    cornerRadius: 50,
    showGuides: false,
    compact: true,
    gravitation: 5,
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (!bubbleContainerRef.current) return;

    // Get the dimensions of the bubble container
    const containerRect = bubbleContainerRef.current.getBoundingClientRect();
    const containerCenterX = containerRect.left + containerRect.width / 2;
    const containerCenterY = containerRect.top + containerRect.height / 2;

    // Calculate the distance from the mouse pointer to the center of the bubble container
    const offsetX = (e.clientX - containerCenterX) * 0.1; // Scale movement for smoother transition
    const offsetY = (e.clientY - containerCenterY) * 0.1; // Scale movement for smoother transition

    // Update the position state to move the bubbles
    setPosition((prevPosition) => ({
      x: prevPosition.x + offsetX,
      y: prevPosition.y + offsetY,
    }));
  };

  useEffect(() => {
    window.addEventListener("mousemove", handleMouseMove);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
    };
  }, []);

  const children = bees?.map((data: any, i: number) => (
    <Child data={data} key={i} />
  ));

  return (
    <div
      ref={bubbleContainerRef}
      className="myBubbleUI h-[300px] rounded-50"
      style={{
        transform: `translate(${position.x}px, ${position.y}px)`,
        transition: "transform 0.1s ease-out", // Smooth out the movement
      }}
    >
      <BubbleUI options={options} className="h-full w-full">
        {children}
      </BubbleUI>
    </div>
  );
}

I kinda worked out to this but the problem is that it moves the entire div not the bubbles :’)

Is there any way that I can make nested div to scroll to mouse pointer direction?