Why is the worker’s onmessage executing after a macro task?

Event loop execution order

I’m studying how the Javascript event loop works for a future presentation, but I’ve come across an unexpected behavior with the information I have so far. Simply put, when I post a message to the worker, the execution of postmessage always occurs after the setTimeout..

script.js:

new Worker('worker.js').postMessage('');

setTimeout( () => {
    const now = new Date().toISOString();
    console.log(`setTimeout execution: ${now}`);
}, 0);

worker.js:

onmessage = function (event) {
    const now = new Date().toISOString();
    console.log(`Worker execution: ${now}`); 
}

If you want to try it in the console by yourself:

const workerCode = `
self.onmessage = function (event) {
  const now = new Date().toISOString();
  self.postMessage("worker executed:     " + now);
}`;

const blob = new Blob([workerCode], { type: 'application/javascript' });
const workerURL = URL.createObjectURL(blob);

const worker = new Worker(workerURL);

worker.onmessage = function (event) {console.log(event.data)};
worker.postMessage('');


setTimeout( () => {
    const now = new Date().toISOString();
    console.log(`setTimeout executed: ${now}`);
}, 0);

My question

Correct me if I’m wrong, but the event loop works in the following order:

  1. Execute all tasks in the call stack
  2. Execute all tasks in the micro task
  3. Execute a task in the macro task
  4. Render graphic/UI

If this is true, knowing that setTimeout is placed in the macro tasks queue, which is literally the last queue to be read, why is the postmessage executed after setTimeout? If during synchronous execution, it is placed in the queue (whatever that queue may be) before setTimeout?

What have I already tried?

I tried to put a delay, but this keeps happening even if setTimeout is delayed, so i believe the cause of this is not the fact that the worker is running in a parallel thread to the main one. Example:

setTimeout( () => {
    const start = performance.now();
    while (performance.now() - start < 1000) { };
    const now = new Date().toISOString();
    console.log(`Execution setTimeout: ${now}`);
}, 0);

how can I create this hover effect

I am fascinated by the hover effect of this website.

https://www.numero8.jp/members/

It’s so beautiful.

I’ve already recreated the smooth photo change with HTML and CSS – that’s not the problem, but I absolutely have no idea how to create this briefly displayed glass effect. Above all, this seems to only refer to the main motif and not the background. Does anyone have an idea or library or something else?

I tried a few times with mix-blend-mode and different animations and combined the whole thing with clip-path but I never got a satisfactory result

How to Implement Loading Spinners for GIF Search Results Like Instagram?

I’m working on a GIF search feature similar to Instagram’s, where users can search for GIFs and see a list of results. Until each GIF is fully loaded, I want to show a loading spinner for the respective GIF.

Right now, my code fetches GIFs using the Tenor API and displays them in a grid layout. However, I don’t have the spinner implementation yet. My goal is to show a spinner for each GIF until it has fully rendered, ensuring a seamless user experience.

Below is my current setup for fetching and displaying GIFs. Can someone guide me on how to implement this behavior efficiently?

The spinner doesn’t need to match exactly like instagram’s, it could be any simple spinner, the idea is to show a loading state.

import { Box, Group, Image, Skeleton, Stack, TextInput } from '@mantine/core';
import { useDebouncedValue } from '@mantine/hooks';
import { useEffect, useState } from 'react';

const GifSelectorModal = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [debouncedQuery] = useDebouncedValue(searchQuery, 400);

  const [gifs, setGifs] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  const searchGifs = async (query: string) => {
    const response = await axios.get('https://tenor.googleapis.com/v2/search', {
      params: {
        q: query,
        key: 'my-key',
        limit: 30,
        client_key: 'tribecrafter',
      },
    });

    return response.data;
  };

  useEffect(() => {
    if (debouncedQuery.length >= 2) {
      setIsLoading(true);

      const fetchGifs = async () => {
        const data = await searchGifs(debouncedQuery);
        setGifs(data.results);
        setIsLoading(false);
      };

      fetchGifs();
    }
  }, [debouncedQuery]);

  return (
    <>
      <TextInput
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
        placeholder="Search GIFs"
      />

      {isLoading ? (
        <Skeletons />
      ) : (
        <Group>
          {gifs.map((gif) => (
            <GifCard key={gif.id} gif={gif} />
          ))}
        </Group>
      )}
    </>
  );
};

const GifCard = ({ gif }) => (
  <Image
    src={gif.media_formats.gif.url}
    alt="GIF"
    onClick={() => console.log('selected gif:', gif)}
  />
);

Desired behaviour:
instagram gif loader screenshot

I tried reading about the onLoad prop for handling when an image has fully loaded, but I’m not sure how to use it in this scenario since I have multiple GIFs loading at the same time. My expectation was to show a spinner for each GIF until it is fully rendered, but currently, all GIFs just appear blank until they finish loading.

Error when using promise to fetch images from AWS in Vue3.js (replit) when deployed

I am trying to fetch images from AWS to display on the resultpage after a user makes a search on the platform.

I am using Vue3.js and am coding on replit. The interesting thing is that this seems to work in development mode but not when deployed.

The error I get is that “TypeError: At.STS is undefined”

How can I resolve this?

Here is the HTML for the resultpage

 <div class="result_list_flow_comp" >
  <div  @click="to_company(result.id)" v-for="(result,idx) in result_list" :key="idx">
    <div class="image_css">
      <img  :src="result.imageUrl" alt="Image" v-if="result.imageUrl" /> 
    </div>
  </div>
 </div> 

Here is the script for the resultpage

import { func } from '@/GetImageFunc.js';
import axios from 'axios'; // Ensure axios is imported

export default {
  data() {
    return {
      result_list: [],
      current_page_nr: 0,
      total_page_nr: 0,
      w: 0,
      category_id: 0,
      page_nr:0,
      lan_id: 0,
      city_filter_activated: false,
      lan_filter_start: false,
    };
  },
  methods: {
    async get_result_companies(category_id, lan_id, page_nr) {
      try {
        const response = await axios({
          method: 'get',
          url: API_URL + 
               '/get_result_companies' +
               '?category_id=' + category_id +
               '&lan_id=' + lan_id +
               '&page_nr=' + page_nr +
               '&city=' + this.city_name,
        });

        // Update result_list
        if (this.lan_filter_activated || this.city_filter_activated) {
          this.result_list = response.data["result_list"].map((item) => ({
            ...item,
            imageUrl: null, // Initialize image URL as null
          }));
        } else {
          this.result_list.push(
            ...response.data["result_list"].map((item) => ({
              ...item,
              imageUrl: null, // Initialize image URL as null
            }))
          );
        }

        // Fetch images asynchronously
        this.result_list.forEach(async (item) => {
          if (item.image) {
            item.imageUrl = await this.get_image(item.id, item.image);
          }
        });

        this.current_page_nr = response.data["current_page_nr"];
        this.total_page_nr = response.data["total_page_nr"];
        this.city_filter_activated = false;
        this.lan_filter_activated = false;
      } catch (error) {
        console.error("Error fetching companies:", error);
      }
    },
    async get_image(id, image) {
      try {
        const data = `enjordrepair_user${id}/${image}`;
        return await func.get_image(data);
      } catch (error) {
        console.error("Error fetching image:", error);
        return null; // Return null if there's an error
      }
    },
    addmore() {
      if (this.current_page_nr < this.total_page_nr) {
        const page_nr = Number(this.current_page_nr) + 1;
        this.get_result_companies(this.category_id, this.lan_id, page_nr);
      }
    },
  },
  watch: {
    "$route.params.id"() {
      this.get_result_companies(this.category_id, this.lan_id, this.current_page_nr);
    },
  },
  mounted() {
    this.w = window.screen.width;
    if (this.lan_filter_start) {
      this.get_result_companies(this.category_id, this.lan_id, 1);
    }
    window.onscroll = () => {
      const bottomOfWindow =
        document.documentElement.scrollTop + window.innerHeight ===
        document.documentElement.offsetHeight;
      if (bottomOfWindow) {
        this.addmore();
      }
    };
  },
};

Here is the code for my GetImageFunc.js

import { S3 } from 'aws-sdk'; 
import Getawsapi from "@/services/getawsapi.service";

export const func = { 
get_image: async (data) => {
    const myBucket = 'mybucket';
    const myKey = data;
    const signedUrlExpireSeconds = 3600 * 1;

    try {
      // Fetch the AWS credentials
      const awsData = await Getawsapi.getAWS2();
             
      const accessKeyId = awsData.AWS_ACCESS_KEY;
      const secretAccessKey = awsData.AWS_SECRET_KEY;
            
      // Initialize the S3 client
      const s3 = new S3({
        signatureVersion: 'v4',
        accessKeyId:accessKeyId, // Resolved value from the promise
        secretAccessKey:secretAccessKey, // Resolved value from the promise
        region: 'eu-north-1',
      });

      // Generate the signed URL
      const url = s3.getSignedUrl('getObject', {
        Bucket: myBucket,
        Key: myKey,
        Expires: signedUrlExpireSeconds,
      });
      return url;

    } catch (error) {
      console.error("Error generating signed URL:", error);
      throw error; // Propagate the error to the caller
    }
      }
    };

Here is the script for getawsapi.service.js

import axios from 'axios';
import {API_URL} from '../../config.js'

export default {
    async getAWS2() {
        try {
            const response = await axios({
                method: 'get',
                url: API_URL + '/getAWSAccessKey'
            });
            return response.data;
        } catch (error) {
            console.error("Error fetching AWS credentials:", error);
            throw error; 
        }
    }
}

Promise() as text in Label

considering:

function calculateDate(input) {
    var result = something_this_takes_too_much_of_the_time * input;
}

Repeater {
    count: 999

    Label {
        text: return (new Promise(resolve =>   calculateDate(somevalue)   )).then(text => text)
    }
}

as far as await function does not work in QML, Promise is good alternative not to block GUI when calculateDate() is calculating and text should be slowly populating one by one

this is at least my udnerstanding of Promise(), never used it before
unfortunatelly, this does not work, it gives me error:

Unable to assign QJSValue to QString

when I try:

return (new Promise(resolve =>   calculateDate()   )).then(text => text.toString())
return (new Promise(resolve =>   calculateDate().toString()   )).then(text => text)

but:

return (new Promise(resolve =>   calculateDate()   )).then(text => text).toString()

only display text as “[object Promise]” – which is expected of course

so how do I achive what I am looking for?

Going directly to URL or refreshing page with URL does not invoke the Angular router

I have two angular components: Program, and MitProgram, each with their own URLs

/landsstaevne/program
/landsstaevne/program/mit-program

My problem is that I can’t directly go to the MitProgram URL (or by refreshing the page), only when going to the Program page first and visiting it from there.

My Angular routing logic is as follows:

.config(function ($locationProvider) {    
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('');
    })
    .value('$routerRootComponent', 'landsstaevneProgram')
    .component('landsstaevneProgram', {
        templateUrl: '/app.html',
        $routeConfig: [
            { path: '/landsstaevne/program/mit-program', name: 'MitProgram', component: 'mitProgram' },
            { path: '/landsstaevne/program', name: 'Program', component: 'program', useAsDefault: true }
        ],

Note: This is using AngularJS

When i go to MitProgram from the Program component, the URL changes as well and the component is displayed on the page. However, when i refresh said page, or enter the URL into a new tab, a 404 page is shown instead.

I’m wondering why the Angular router is not picking up this URL and routing me to the correct component as specified in the route config.

Navigation to the MitProgram component from the Program component:

<div
      ng-link="['MitProgram']"
      title="Mit program"
      class="btn btn-link-program icon icon-custom-heart"
    >
      Mit program
    </div> 

I only succeed once out of 10 times when using solana.js to perform swap transactions?How to prove it

I use quicknode metis jup to get quotes to build swaps, and trade through quicknode’s solana nodes.I tried a lot, and even if I set the quote slippage parameter and swap priority fee to automatic, my transaction success rate was still low.Many transactions cannot be found on the chain at all, as if nothing happened.Below are the parameters I currently use to obtain quotes and build swaps:

`const params = {
        inputMint: "So11111111111111111111111111111111111111112",
        outputMint: "9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump",
        amount: 10000000,
        slippageBps: 20,
        onlyDirectRoutes: true,
        autoSlippage: true
    };
    const quote = await jupiterTrader.getQuoteBase(params);`
`async getSwapTransaction(quoteResponse) {
    return await promiseRetry(async (retry) => {
        try {
            const response = await fetch('https://quote-api.jup.ag/v6/swap', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    quoteResponse,
                    userPublicKey: this.wallet.publicKey.toString(),
                    wrapAndUnwrapSol: true,
                    dynamicComputeUnitLimit: true,
                    prioritizationFeeLamports: 'auto'
                })
            });

            if (!response.ok) {
                throw new Error(`API请求失败: ${response.status}`);
            }

            return response.json();
        } catch (error) {
            return retry(error);
        }
    }, this.RETRY_OPTIONS);
}`

I want to achieve a 90% success rate in my transactions. I mainly trade mainstream currencies through JUP’s API, and I am willing to pay priority fees. I hope you can share some good code snippets or point out problems with my code.

React router scroll reset

How can I make a page in React render scrolled to the top immediately during routing? I’m using the useLayoutEffect hook, but it triggers only after the page is rendered: first, I see the rendered page, and only then the scroll-to-top function executes. How can I ensure the page is displayed already scrolled to the top on load?

This is my component :

import { useLayoutEffect } from "react";
import { useLocation } from "react-router-dom";

const ScrollToTop = () => {
  const { pathname } = useLocation();

  useLayoutEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
};

export default ScrollToTop;

How can I get my navbar-on-scroll effect to work in next.js?

I am in the middle of transferring my project from Vite + React to Next.js and I am trying to create a changeColourOnScroll function on my Navbar.jsx component but it’s not working. Here is my Navbar.jsx with Vite + React (That Works).

Navbar.jsx (Vite + React, this works):

// Array that features all nav-links required. Will return in .map component
const navigation = [ 
  {_id:101, title: 'HOME', href: '/'},
  {_id:102, title: 'ABOUT US', href: '/AboutUs'},
  {_id:103, title: 'SHOP', href: '/Shop'},
  {_id:104, title: 'MENU', href: '/Menu'},
  {_id:105, title: 'CONTACT US', href: '/ContactUs'},
];

const Navbar = () => {
    const { pathname } = useLocation();
    const active = useLocation().pathname; // returns current location and url
    const [colour, setColour] = useState(false); // changes the state of colour upon scrolling
    const [cartOpen, setCartOpen] = useState(false) // Opens and closes cart

    const close = () => setCartOpen(false);
    const open = () => setCartOpen(true)

    useEffect(() => {
      close();

      const changeColour = () => {
        const isHome = matchPath("/", pathname)
        const isAboutUs = matchPath("/AboutUs", pathname)
        ...

          if (isHome && window.scrollY >= 650) {
            setColour(true)
        } else if (isAboutUs && window.scrollY >= 1) {
            setColour(true)
        } ...
      }; 
      
      // invoke once to check in case page is already scrolled down when rendering
      changeColour();
      window.addEventListener('scroll', changeColour);

      return () => {
        window.removeEventListener('scroll', changeColour)
      }
    }, [pathname])

return (
  <div className={`${colour ? 'navbar navbarbg' : 'navbar'}`}>
    ...
  )
}

Here is my Navbar.jsx (Next.js, this doesn’t work):

const navigation = [ 
  { _id:101, title: 'HOME', href: '/' },
  { _id:102, title: 'ABOUT US', href: '/about' },
  { _id:103, title: 'SHOP', href: '/shop' },
  { _id:104, title: 'MENU', href: '/menu' },
  { _id:105, title: 'CONTACT US', href: '/contact' },
];

const Navbar = () => {
  const { pathname } = usePathname();
  const [colourOnScroll, setColourOnScroll] = useState(false); // changes the state of colour upon scrolling
  const [cartOpen, setCartOpen] = useState(false) // Opens and closes cart

  const close = () => setCartOpen(false);
  const open = () => setCartOpen(true)

  // colourOnScroll logic
  const changeColourOnScroll = () => {
    const scrollThresholds = {
      '/': 650,
      '/about': 1,
      ...
    };

    const threshold = scrollThresholds[pathname] || 0;
    if (window.scrollY >= threshold) {
      setColourOnScroll(true)
    } else {
      setColourOnScroll(false)
    }
  }

  useEffect(() => {
    close();    
    const handleScroll = () => {
      changeColourOnScroll();
    }
    changeColourOnScroll(); // Invoke on scroll mount

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [pathname])
    
  return (
    <div className={`${colourOnScroll ? 'navbar navbarbg' : 'navbar'}`}>
     ...
  )

What am I doing wrong? And yes I have imported usePathname from 'next/navigation' instead of 'useLocation'

Create a website that show data read from an excel file and get updated periodically

I need to create a website (also local one is fine) that reads an excel file and shows the content into a table and update the contents periodically.

I have already written something but it doesn’t update the content of the website periodically as it should.
Can you help me?

This is how the page select and read the file:

document.getElementById('file-input').addEventListener('change', function (event) {
    const file = event.target.files[0];
    if (file) {
        lastModified = new Date(file.lastModified);
        const reader = new FileReader();
        reader.onload = function (e) {
            fileData = new Uint8Array(e.target.result);
            updateTable();
        };
        reader.readAsArrayBuffer(file);
    }
});

function updateTable() {
    if (fileData) {
        const workbook = XLSX.read(fileData, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        const tableBody = document.getElementById('excel-data');
        tableBody.innerHTML = '';

        jsonData.forEach((row, rowIndex) => {
            if (rowIndex === 0) return; // Skip header row
            const tr = document.createElement('tr');
            row.forEach(cell => {
                const td = document.createElement('td');
                td.className = 'py-2 px-4 border-b border-gray-200';
                td.textContent = cell;
                tr.appendChild(td);
            });
            tableBody.appendChild(tr);
        });

        document.getElementById('last-modified')
          .textContent = `Data ultima modifica del file Excel: ${lastModified.toLocaleString()}`;
    }
}

this is how it should get updated every 5 minutes:

setInterval(() => {
    if (fileData) {
        updateTable();
    }
}, 300000);

Using the the debugger the function updateTable() seems to be called and get redirected to the following tailwind function

new MutationObserver(async r => {
        let e = !1;
        if (!cf) {
            cf = new MutationObserver(async () => await pf(!0));
            for (let t of document.querySelectorAll(`style[type="${uf}"]`))
                Pv(t)
        }
        for (let t of r)
            for (let i of t.addedNodes)
                i.nodeType === 1 && i.tagName === "STYLE" && i.getAttribute("type") === uf && (Pv(i),
                e = !0);
        await pf(e)
    }

but after this no contents gets updated although the excel file got modified in the meanwhile.

moving function to class throws Uncaught SyntaxError: Unexpected token ‘{‘ in chrome extension

I’m creating a Chrome extension as a test and bundle my js with webpack.
Everything worked fine when the js was into separate functions but as soon as I moved it into a class i started getting the following error:

enter image description here

The error is triggered when I open the chrome extension dropdown.

The class:

class FetchData {
    init() {
        console.log("chrome tabs class", chrome.tabs);
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            console.log("Execute Script CLASS");
            chrome.scripting.executeScript({
                target: { tabId: tabs[0].id },
                func: this.getImages
            }, (result) => {
                console.log("Result CLASS", result);
                if (result[0].result !== null) {
                    this.paintImageList(result[0].result);
                }
            });
        });
    }

    getImages() {
        console.log("getImages");
    }

    paintImageList (results) {
        document.getElementById("image-count").innerHTML = results.length;
    }
}

module.exports = FetchData;

My webpack config:

const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
    mode: "development",
    devtool: 'cheap-module-source-map', // fixes 'unsafe-eval' CSP issue
    entry: {
        "/extension/image-downloader/style": __dirname + "/assets/scss/style.scss",
        "/extension/image-downloader/app": __dirname + "/assets/js/app.js",
    },
    output: {
        path: path.resolve(__dirname),
    },
    plugins: [
        new CopyPlugin({
            patterns: [
                { from: "node_modules/bootstrap-icons/font/fonts/", to: "extension/image-downloader/fonts" },
            ],
        })
    ],
};

Mapping a object and return the index with result [closed]

Using this code – seen on a previous closed thread – how would you also return the index of the new order from the new mapped object?

The venue_code map of the works fine and produces the correct result.

I then want to map the result to find the indexes of the venue_code.indexOf(venue_code[n]).

mainArray = [
    { code: 1, name: 'AC Milan' },
    { code: 2, name: 'Juventus' },
    { code: 3, name: 'AS Roma' },
    { code: 4, name: "Napoli"},
    { code: 9, name: "Inter Milan"}
];

filterArray  = [4, 1, 3, 2];

const venue_code   = filterArray.map(c => mainArray.findIndex(v => c === v.code));

for(n=0; n<venue_code.length; n++){
    document.write(venue_code[n]+" * "+venue_code.indexOf(venue_code[n])+"<br/>");
};

// Also return the indexes of the new map, e.g, second column.

ApexCharts type line – background color

i have a simple js, html file, im using ApexCharts and want to handle the positive and negative parts of chart.

3 things about it:

  1. markers style (handled already)
  2. line color (handled already)
  3. the background gradient below the line (problem)

is there any way to add a background to the line type chart below the line?

  <div id="chart"></div>
  <script src="exp.js"></script>
const dataPoints = [-10, 3, -5, -18, -10, 12, 8]

const discreteMarkers = dataPoints.map((value, index) => {
  return {
    shape: "circle",
    size: 4,
    seriesIndex: 0,
    dataPointIndex: index,
    fillColor: "#ffffff",
    strokeColor: value >= 0 ? "#157446" : "#C13446",
    strokeWidth: 1,
  };
});

var options = {
  chart: {
    height: 380,
    type: "line",
    foreColor: '#aaa',
    zoom: {
      type: 'x',
      enabled: true,
      autoScaleYaxis: true
    },
  },
  series: [
    {
      name: "Series 1",
      data: dataPoints
    }
  ],
  stroke: {
    width: 5,
    curve: "monotoneCubic"
  },
  plotOptions: {
    line: {
      colors: {
        threshold: 0,
        colorAboveThreshold: '#157446',
        colorBelowThreshold: '#C13446',
      },
    },
  },
  markers: {
    discrete: discreteMarkers
  },
  grid: {
     borderColor: '#6D6D6D',
     strokeDashArray: 3,
  },
  xaxis: {
    categories: [
      "01 Jan",
      "02 Jan",
      "03 Jan",
      "04 Jan",
      "05 Jan",
      "06 Jan",
      "07 Jan"
    ]
  },
  stroke: {
      curve: 'smooth',
      width: 2
  },
};

var chart = new ApexCharts(document.querySelector("#chart"), options);

chart.render();

here is a link to check output.
https://codepen.io/amirdoosti/pen/RNbQWPK

threejs canvasTexture is blurry meanwhile the origin canvas is not

I’m using canvas as texture to render a plane, but canvasTexture on plane is a little blurry. How to fix blurry part?

render result picture

Here is the JS code:

html code picture

js code picture

import * as THREE from "three";

const image = document.getElementById('origin-img')

/* --- draw 【canvas】 by image--- */
const canvas = document.getElementById('canvas')
canvas.width = image.width
canvas.height = image.height
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, image.width, image.height)

/* --- threejs scene --- */
const itemWidth = 300
const itemHeight = 300

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(itemWidth / - 2, itemWidth / 2, itemHeight / 2, itemHeight / - 2, 0, 1000);
camera.position.z = 100;

const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('webgl'), antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(itemWidth, itemHeight);

// create a plane which uses 【canvas】 as texture
const geometry = new THREE.PlaneGeometry(image.width, image.height, 64, 64);
const material = new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(
        canvas,
        THREE.Texture.DEFAULT_MAPPING,
        THREE.ClampToEdgeWrapping,
        THREE.ClampToEdgeWrapping,
        THREE.LinearFilter,
        THREE.LinearMipmapLinearFilter,
        THREE.RGBAFormat,
        THREE.UnsignedByteType,
        1
    )
});
const plane = new THREE.Mesh(geometry, material);
scene.add(plane);

renderer.render(scene, camera);

Had tried to change the THREE.CanvasTexture‘s paramaters, but it’s still a little bit blurry.

Mantine Menu not opening

I’m using menu from mantine in my navbar for a login button which when clicked fetches my porfile picture from auth0 login, however the menu dropdown is not working, it should be opening the menu when clicked but it does. In the inspect tab it shows the button tags for the menu dropdown when clicked but does not reflect that on the UI.

function ProfileMenu({ user, logout }) { return ( <Menu shadow="md" width={200} opened> <Menu.Target> <Avatar radius="xl" src={user?.picture || null} alt={user?.name || 'User Avatar'} styles={{ image: { borderRadius: '50%', width: '40px', height: '40px', cursor: 'pointer' } }} /> </Menu.Target> <Menu.Dropdown styles={{ zIndex: '12000' }}> <Menu.Item>Favorites</Menu.Item> <Menu.Item>Bookings</Menu.Item> <Menu.Item onClick={() => { localStorage.clear(); logout(); }}>Logout</Menu.Item> </Menu.Dropdown> </Menu> ); }

I tried adding the z-index property but it didn’t work.
<Menu.Dropdown styles={{ zIndex: '12000' }}>