I want Image back to its original position in FabricJs library

I am looking for to solve one final issue in this. If you zoom in at one point and then zoom out at some other point on the canvas the image doesn’t come back to the original position(centre of the canvas).
Also set the maximum zoom out to 1.
If anyone have solution for my problem then solve it, its very urget.

This is my code:

const canvas = new fabric.Canvas("canvas",{
    width:700,
    height:450,
    backgroundColor:"grey"
    // selection:false
});

canvas.on('mouse:wheel', function(opt) {
    var delta = opt.e.deltaY;
    // console.log(delta)
    var zoom = canvas.getZoom();
    // console.log(zoom)

    zoom *= 0.999 ** delta;
    if (zoom > 40) zoom = 40;
    if (zoom < 1) zoom = 1;
    canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
    opt.e.preventDefault();
    opt.e.stopPropagation();
});
canvas.renderAll();

//get image from user

var upload_image="";
const image = document.querySelector("#image"); 

image.addEventListener("change",()=>{
    // console.log(image.files)
    const reader = new FileReader();

    // console.log(reader)
    reader.addEventListener("load",()=>{
        upload_image=reader.result;
    })
    reader.readAsDataURL(image.files[0]);
});


const setImage =() =>{
  setImg();
}
const setImg = ()=>{
  // canvas.backgroundImage=img;
  fabric.Image.fromURL(upload_image,(img)=>{
    // img.width=500;
    // img.height=500;
    canvas.backgroundImage=img;
    img.center();
    img.centerV();
    img.centerH();
    canvas.renderAll();
    // canvas.add(img);
});
}

my html code:

<body class="center">
    <div class="container center">
        <H1>IMAGE zoom IN and OUT</H1>
        <div id="canva">
            <canvas id="canvas"></canvas>
        </div>
        <input type="file" accept="image/*" id="image">
        <button id="btn" onclick="setImage()">Upload Image</button>
    </div>
  
    <script src="fabric.min.js"></script>
    <script src="index.js"></script>

</body>

how to iterate through nested object which is inside an array in javascript

I want to iterate through imageUrl and keep each element inside li tag. I’m fetching only one element based on some condition, in the array then I want to iterate through all the images
my array

const productsArr = [
    {
      id: "p1",
      title: "Colors",
      price: 100,
      imageUrl: {
        imageUrl1:
          "img/Album%201.png",
        imageUrl2:
          "img/Album%202.png",
        imageUrl3:
          "img/Album%203.png",
        imageUrl4:
          "img/Album%204.png",
    },
    },

    {
      id: "p2",
      title: "Black and white Colors",
      price: 50,
      imageUrl: {
        imageUrl4:
          "img/Album%205.png",
        imageUrl1:
          "img/Album%206.png",
        imageUrl2:
          "img/Album%207.png",
        imageUrl3:
          "img/Album%208.png",
      },
    },]

code to iterate through the array. I think I should not use map here but I could not come up with the solution.

console.log(product);
 const productImage= product[0].imageUrl.map(element => {
   return <li>{<img src={element} alt={product[0].title}/>}</li>
 });

Getting the color of a pixel on an image

I’ve been trying to figure out a solution to a problem I am having. I simply just want to get the color of a specific pixel on a JPEG in JavaScript. Is there a good way I can do this? All solutions I find online talk about manipulating a canvas, or changing the colors of a canvas element, but I simply want to find a pixel color on an image.

Thank you for any help and insight!

Is there a way to detect configuration changes in Plasma desktop scripts?

I want to create a background script that syncs configuration between taskbars in KDE Plasma. Here’s the JS I have so far:

const onTaskbarUpdate = function() {
    print("Ding!n")
}

for (let p of panels()) {
    for (let w of p.widgets()) {
        if (w.type === "org.kde.plasma.icontasks") {
            // call onTaskbarUpdate whenever w changes config
        }
    }
}

In other words, I want to call onTaskbarUpdate whenever the configuration changes. Documentation is sparse, and there isn’t much pointing to a solution. How would I do it?

NOTE: if an auxiliary shell script is needed, that works too.

React native stack navigator : how to pass params?? i can’t pass params

enter image description here

this is structure of project.
i want to operate it: when is press ReportButton, navigate to ReportScreen with post’s title parameter(props)

this is stack of App.js

<NavigationContainer>
        <Stack.Navigator initialRouteName="Main">
          <Stack.Screen name="Main" component={MainScreen} />
          <Stack.Screen name="Report" component={ReportScreen} />
        </Stack.Navigator>
      </NavigationContainer>

this is tap navigator of mainscreen

<Tab.Navigator initialRouteName="Home" tabBarOptions={{showIcon: true}}>
      <Tab.Screen
        name="Main"
        options={{
          tabBarLabel: 'main',
          tabBarIcon: ({color}) => <Icon name="home" color={color} size={24} />,
          tabBarColor: 'blue',
        }}
        component={MapScreen}
      />
      <Tab.Screen
        name="Feed"
        options={{
          tabBarLabel: 'feed',
          tabBarIcon: ({color}) => <Icon name="home" color={color} size={24} />,
          tabBarColor: 'blue',
        }}
        component={FeedScreen}
      />
      <Tab.Screen
        name="Setting"
        options={{
          tabBarLabel: 'setting',
          tabBarIcon: ({color}) => <Icon name="home" color={color} size={24} />,
          tabBarColor: 'blue',
        }}
        component={SettingScreen}
      />
</Tab.Navigator>

this is part of ReportButton to navigate

    <TouchableOpacity
        style={postModalStyles.listButton} 
        onPress={()=>{console.log(post.title); navigation.navigate('Report', { title: post.title 
    });}}>
                <Text style={postModalStyles.text}>report</Text>
    </TouchableOpacity>

this is part of ReportScreen

const ReportScreen = ({title}) => {
   console.log(title);
   return(
     <View></View>
   );
}

output of node.js console

 LOG  hello world //log of reportbutton 's post.title
 LOG  undefined //log of reportscreen's post.title

How do you add a key to a variable map in javascript?

How would I add a key to a mapped variable statement like below?

  const limit = Math.max(...props.data.map(x => x.count), 0);

I’m getting an error in React stating “Each child in a list should have a unique “key” prop.” I know how to add a key to an HTML object, but I’m not sure how to do it in this case.

MongoDB authentication not working due to dotenv

I am trying to load the following from the .env file to index.js for MongoDB authentication.

DB_USER:(my user name here)
DB_PASS:(my password here)

I have checked and there are apparently no issues with the user name and password.

I have also added require('dotenv').config(); and process.env.DB_USER, process.env.DB_PASS to my index.js.

The program shows the following error, where I have used console.log() to display contents of the uri for MongoDB.

mongodb+srv://undefined:undefined@[here goes my link to mongodb]
Listening to port  5000
MongoServerError: bad auth : Authentication failed.
    at Connection.onMessage (F:Projectsema-john-servernode_modulesmongodblibcmapconnection.js:203:30)
    at MessageStream.<anonymous> (F:Projectsema-john-servernode_modulesmongodblibcmapconnection.js:63:60)
    at MessageStream.emit (node:events:390:28)
    at processIncomingData (F:Projectsema-john-servernode_modulesmongodblibcmapmessage_stream.js:108:16)
    at MessageStream._write (F:Projectsema-john-servernode_modulesmongodblibcmapmessage_stream.js:28:9)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at MessageStream.Writable.write (node:internal/streams/writable:334:10)
    at TLSSocket.ondata (node:internal/streams/readable:754:22)
    at TLSSocket.emit (node:events:390:28) {
  ok: 0,
  code: 8000,
  codeName: 'AtlasError',
  [Symbol(errorLabels)]: Set(0) {}
}

Youtube data api search issue, next page results contain same videos

  • I used youtube data api returning search result. And to get more result, I used nextPageToken as param. => when a btn i made clicked, showing next page’s 5 videos.
  • It actually works, but some next page results contain previous page’s videos.
  • for example, I expected if 3rd page videos are a, b, c, d, e, 4th page items are f, g, h, i, j.
  • but 4th page’s like a, f, g, h, i or something. I’m not sure there is any rules or not.

has anyone experienced and solved this problems?

Issue with anchor links on homepage

Im having issues with the anchor links on my homepage.

I have the following menu, which works great when the user is on the homepage but when visiting another page and clicking the “About” link it doesnt goto the homepage to find the anchor.

<nav class="main-menu">
        <a href="/#about">About</a>
        <a href="/contact">Contact</a>
</nav>

If I change the menu to the following, it works great when are on other pages, but when on the homepage (the url to my homepage is www.mysite.com/ (with nothing after the /)) and clicking “About” it loads the page again before going to the anchor point.

<nav class="main-menu">
        <a href="/home#about">About</a>
        <a href="/contact">Contact</a>
</nav>

Have been looking for a solution whereby:

  • When someone arrives at the homepage of my site (full url: www.mysite.com/) they can click “About” and will goto the anchor point (without refreshing the page).
  • When the user clicks “About” from a different page he will go back to
    the anchor point on the homepage (www.mysite.com/).

Many thanks in advance!

Why is declaring a variable outside of the loop more faster?

A few weeks ago, I heard that declaring the true/false condition variable outside of the loop was faster. So, I wanted to try it out.


So, basically, I made this code to see which is faster.

These are the two loops.

// Initialization
const arr = [1, 2, 3, 4, 5];

// Bad Loop
console.time("bad");

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

console.timeEnd("bad");

// Good Loop
console.time("good");

let l = arr.length;
for (let i = 0; i < l; i++) {
  console.log(arr[i]);
}

console.timeEnd("good");

When the code is run, there is a significant difference in the time it takes to run the bad loop, versus the time it takes in the good loop. (No matter how quick the bad loop is, the good loop is always quicker.)


So, my question is why is this happening? The only difference between the two loops is the fact that the good loop defines the array length before the loop begins, while the bad loop gets it in the loop.

Passing mapped data from api call to child

Once again im asking so to help me get unstuck lol. Im making a recipe type page for my portfolio, I wanted to make it so you can search burgers for example, get recipes then select one and view it. the way its currently set up is you land useEffect shows some place holder data. You search it makes a api call then maps the data into cards, I want it so when you click a recipe it sends the id down to the child page for specific recipes. because the api im using you cannot do general searchs and recipe specific without the id number. So my idea was when you click a recipe it sends the recipe id down to a child and takes you to the page on the same click. im not sure if this is possible or im doing something wrong? ill either get every card id multiple times or none. im currently only testing this functionality with the placeholder data. any help or ideas is greatly appreciated.

app.js 
 async function searchRecipes(){
    const response = await fetch('https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/complexSearch?query='+searchedRecipe+'&ranking=2', options)
    const recipeData = await response.json()
    //console.log(recipeData)
    setSearchedResults(recipeData.results)
    setShowPlaceHolder(false);
  }

//function to create placeholder recipe card.
  function createPlaceHolderCard(placeHolderRecipe , n){
    return(
      <Card 
      key = {n}
      id = {placeHolderRecipe.id}
      image ={placeHolderRecipe.image}
      title = {placeHolderRecipe.title}
      send={setId}

      />

    )

  }

  //function to create searched cards

  function createSearchedCard(searchedResults, n){
    return(
      <Card 
      key = {n}
      id = {searchedResults.id}
      image = {searchedResults.image}
      title={searchedResults.title}

      />
    )
  }


  //function to pass recipe id down to card.

  function sendRecipe(recipeID){
    return(
      <UserRecipe 
        id={recipeID}

      />
    )
  }

  //set recipe id 

  function setId(id){
    setRecipeID(id)
    console.log(id)
    sendRecipe()
  } 

Card.js

function Card(props) {
    const[ id, setId] =useState('')


    function x (){
        setId(props.id)
    }
    
  return (
    <div>

        <h1>{props.title}</h1>

        <img src={props.image} alt="" />

        <Link to='/searchedrecipe' ><button onClick={()=> {x(); props.send(id);} }>View recipe</button></Link>

    </div>
  )
}

selected recipe page

useEffect (()=>{
        try{
          async function getRecipes(){
            const response = await fetch('https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/'+props.id+'/information', options);
            const recipeData = await response.json()
            setDetaiedRecipe(recipeData)
          }getRecipes()
        }catch(error){
          console.log(error);
        }
      }, [])
    
  return (
    <div>
    <h1>{detailedRecipe.title}</h1>
    <p>{detailedRecipe.summary}</p>
    </div>
  )

select api response with a condition angular javascript

I have an api response that gets me an object and inside that object I have an array called “employes” ,”employes” has an item called “avis” .
I want to select the object when the value inside of employes>recrutments>avis=”accepter” .
enter image description here
enter image description here

I tried to map on the response and I used every method of JavaScript

getJuction():void{
  this.getAlloff.getjuction()
  .subscribe(data => {

    console.log(data);
    
    this.test = data.map(function(element:any){
   
      return element.employes.map((employe:any)=>employe.recrutements.avis === 'accepter').every((emel:any) => emel === true ) ;
     
      
      });
      console.log(this.test)
      var test2 = data.filter((employe:any)=>employe);
      console.log(test2)
      
    // var test =data.flat();
    // console.log(test)
    
    

  }, error => console.log(error));

}

This is the result I get.

The only object that has “accepter” for every value gets true

enter image description here