threejs how to adjust 3d object camera position on scroll

hey guys i am new to threejs and i am currently trying to adjust my camera angle such that it pulls itself backwards on scroll up to a certain level. i am trying to make it such that the 3d object becomes smaller on scroll by adjusting the camera angle. is there anyway to do that? thanks in advance

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3d model</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  

  <body>
    <script type="module">
        import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
        
        import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
        import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/GLTFLoader.js';
        import { RGBELoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/RGBELoader.js';
        
        var container, controls;
        var camera, scene, renderer, mixer, clock;
        var obj
        
        init();
        animate();
        
        function init() {
        
          container = document.getElementById( 'test' );
          document.body.appendChild( container );
          
          

          camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.01, 1000 );
          camera.position.set(0, 20, 30);

        
          scene = new THREE.Scene();
          scene.background = new THREE.Color(0xffffff);
          var light = new THREE.HemisphereLight(0xffffff,0x000000,10);
          scene.add(light);



          
          clock = new THREE.Clock();
        
              // model
          
              var loader = new GLTFLoader();
              loader.load( 'dinosaur.glb', function ( gltf ) {
        
                obj = scene.add( gltf.scene );
        
                mixer = new THREE.AnimationMixer( gltf.scene );
                
                gltf.animations.forEach( ( clip ) => {
                  
                    mixer.clipAction( clip ).play();
                  
                } );
        
              } );
        
        
          renderer = new THREE.WebGLRenderer( { antialias: true } );
          renderer.setPixelRatio( window.devicePixelRatio );
          renderer.setSize( window.innerWidth, window.innerHeight );
          renderer.toneMapping = THREE.ACESFilmicToneMapping;
          renderer.toneMappingExposure = 0.8;
          renderer.outputEncoding = THREE.sRGBEncoding;
          container.appendChild( renderer.domElement );
        
        
          controls = new OrbitControls( camera, renderer.domElement );
          controls.minDistance = 2;
          controls.maxDistance = 10
          controls.target.set( 0, 0, - 0.2 );
          controls.update();
        
          window.addEventListener( 'resize', onWindowResize, false );


          function rotateFunction() {
        obj.rotation.y += 0.02;        
        console.log(obj)
        
      }

      document.addEventListener('scroll', function(e) { rotateFunction() });


        
        }
        function onWindowResize() {
          camera.aspect = window.innerWidth / window.innerHeight;
          camera.updateProjectionMatrix();
        
          renderer.setSize( window.innerWidth, window.innerHeight );
        }
        
        //
        
        function animate() {
          requestAnimationFrame( animate );
          var delta = clock.getDelta();
          if ( mixer ) mixer.update( delta );
          renderer.render( scene, camera );
        
        }

        function adjustCamera() {
          console.log('test')

        }

        document.addEventListener('scroll', function(e) { adjustCamera() });



        </script>
  </body>
  <div id="test">

  </div>

  <div id="test2">

    testing121

  </div>

</html>

Do React child components always need to be stateful?

When a child component’s sole purpose is to consume its parent’s state, does it need to be stateful itself?

Looking at these two examples:

“Stateless”

const ServicesCard = ({ service, onClick, isPro = false }) => {
  const name = isPro && service.pro?._id ? service.pro.pro_name : service.name;
  let price = isPro && service.pro?._id ? service.pro.total : service.total;

  // Special case scenarios
  let prefix;
  let suffix;

  if (service.hasPages) {
    prefix = 'from';
  }
  if (service.uid === 'abcdef') {
    prefix = '';
    price = `${price} per page`;
    suffix = '($5 minimum)';
  }
  if (service.uid === 'qwerty') {
    suffix = "+ gov't fees";
  }

  return (
    <div className={styles.servicesCard} onClick={onClick}>
      <h1 className={styles.header}>{name}</h1>
      <p className={styles.pricing}>
        <span className={styles.prefix}>{prefix}</span>
        <span className={styles.price}>{`$${price}`}</span>
        <span className={styles.suffix}>{suffix}</span>
      </p>
    </div>
  );
};

Stateful

const ServicesCard = ({ service, onClick, isPro = false }) => {
  const [name, setName] = useState('');
  const [price, setPrice] = useState('');
  const [prefix, setPrefix] = useState('');
  const [suffix, setSuffix] = useState('');

  useEffect(() => {
    const _name = isPro && service.pro?._id ? service.pro.pro_name : service.name;
    let _price = isPro && service.pro?._id ? service.pro.total : service.total;

    // Special case scenarios
    let _prefix;
    let _suffix;

    if (service.hasPages) {
      _prefix = 'from';
    }
    if (service.uid === 'abcdef') {
      _prefix = '';
      _price = `${_price} per page`;
      _suffix = '($5 minimum)';
    }
    if (service.uid === 'qwerty') {
      _suffix = "+ gov't fees";
    }

    setName(_name)
    setPrice(_price)
    setPrefix(_prefix)
    setSuffix(_suffix)
  }, [service]);

  return (
    <div className={styles.servicesCard} onClick={onClick}>
      <h1 className={styles.header}>{name}</h1>
      <p className={styles.pricing}>
        <span className={styles.prefix}>{prefix}</span>
        <span className={styles.price}>{`$${price}`}</span>
        <span className={styles.suffix}>{suffix}</span>
      </p>
    </div>
  );
};

I feel like both of them would behave the same, since a re-render will be triggered by a state change higher up in the tree anyways, forcing everything to be recalculated. React also emphasizes that Data flows down.

Provided that service is the only prop that changes, why should I use more browser memory by using the useState & useEffect React APIs?

How do I solve JavaScript execution error in Johnny-five?

Original post: How do I fix johnny 5 installation error?

When I run my JS file I get this error:

1637373588955 Available COM3 
1637373588956 Connected COM3 
1637373592592 Repl Initialized 
>> 1637373598958 Device or Firmware Error A timeout occurred while connecting to the Board. 

Please check that you've properly flashed the board with the correct firmware.
See: https://github.com/rwaldron/johnny-five/wiki/Getting-Started#trouble-shooting

If connecting to a Leonardo or Leonardo clone, press the 'Reset' button on the board, wait approximately 11 seconds for complete reset, then run your program again. 
events.js:306
    throw err; // Unhandled 'error' event
    ^

I’ve already tried installing different Firmata software but it isn’t helping. What do you think?

Do styles components use JSX?

I am learning to use react and styled components. While using the styled components package to create a button element, the React import at the top of my code editor gives a warning that react is defined/declared but never used.

Isn’t creating a html button and assigning it to a javascript variable JSX ?
Do styled components already have the JSX logic built in ?
Kindly help clear this doubt.
Thanks.

import React from 'react';
import styled from 'styled-components';

const Button = styled.button`
  font: inherit;
  padding: 0.5rem 1.5rem;
  border: 1px solid #8b005d;
  color: white;
  background: #8b005d;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.26);
  cursor: pointer;

&:focus {
  outline: none;
}

&:hover,
&:active {
  background: #ac0e77;
  border-color: #ac0e77;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
}
`

export default Button;

How would I add data on a button press to the either the root or a component of Vue 3?

My main problem is that I’m trying to reactively add data to either the Vue root or a Vue component. The reason this is an issue is because once my Vue app instance is mounted, (using app.mount()), I am unable to reactively add data to the Vue application. I am trying to use Vue along with vanilla JS as I am a novice with the framework. I guess what it really comes down to is… is there any event I could trigger or object I could call in vanilla JS to insert new data into lets say an array of objects within the Vue app instance?

Images are not showing when clicking on canvas (JavaScript)

I am having an issue displaying images on a canvas when it clicks. I am using a bit of Ajax as well to get the city names from an array of JSON Objects (these city names correspond to different plane images that I am trying to display).

For example when I click the canvas nothing appears on the canvas but when I go to inspect element/network it shows that its getting the images.

This is what shows when I click the canvas, as you can see it still gets the images but doesn't display them.

The code that I used to display the images:

function drawPlanes() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var max = 1000;
var min = 553;
var cityNames = schedule["cities"];
var randomCity = cityNames[Math.floor(Math.random()*cityNames.length)].city;

var planeImage = new Image();
planeImage.onload = function() {
    ctx.drawImage(planeImage, Math.random() * (max - min) + min, Math.random() * (max - min) + min);
};
planeImage.src = findImage(randomCity);
}

This is the findImage function that I use to determine what Image it is and from that write the source:

function findImage(cityNames) { 
if (cityNames == "Iqaluit" || cityNames == "Whitehorse" || cityNames == "Yellowknife") {
    return "img/plane.jpg";
}
    
if (cityNames == "Halifax" || cityNames == "Charlottetown" || cityNames == "Winnipeg" 
        || cityNames == "Regina" || cityNames == "Edmonton" 
            || cityNames == "Victoria" || cityNames == "Toronto") {

    return "img/" + cityNames.toLowerCase() + ".jpg";
}

if (cityNames == "Fredericton" || cityNames == "Ottawa" || cityNames == "Quebec") {
    return "img/" + cityNames.toLowerCase() + ".png";

}

if (cityNames == "St. John") {
    return "img/stjohn.jpg";
}}

In summary I am just having an issue actually displaying the images on the canvas when it is clicked. Hope this is clear.

why code disappear from console when I run the event click [duplicate]

this is js code with some ids from my HTML page
when I press the button with click event the function doesn’t work and the code in the console disappear

let users = [{user:" moh ", password: " 1234 "}, {user:"Jouza", password: "5678"} ]

const name1 = document.querySelector("#Text")

const pass = document.querySelector("#pass1")

const login1 = document.querySelector("#btn")

const paragraph = document.querySelector("#par")

function verify(){

console.log("verify called")
const currentUser = name1.innertext.value
const currentpassword = pass.innertext.value

for(let i = 0; i>users.length; i++){
if( users[i].user === currentUser && users[i].password === currentpassword){

paragraph.innertext="Login Success";

`paragraph.style.backgroundColor="green";`

`return;`

}
}

paragraph.innertext="Login Failed";

paragraph.style.backgroundColor="red";

return;

}

login1.addEventListener("click",verify)

Applying CSS class to a Javascript

First off I just wanna state that I know next to nothing when it comes to Javascript so forgive me if I use the wrong jargon.

I’m trying to do a layout for tumblr where the sidebar image will change upon refresh.
I’m using an existing layout and following another tutorial on how to achieve the effect.

The CSS class for the sidebar is called “side-img”.

The CSS from the original layout is as below

<img class="side-img" src="{image:Sidebar Image}">  

From another tutorial, I’m asked to replace it with the following code to get the changing sidebar image working.

<script language="JavaScript">
<!--
 
 
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="IMAGE URL"
myimages[2]="IMAGE URL"
myimages[3]="IMAGE URL"
 
 
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>

The sidebar image does change upon refresh but now it also loses all the CSS class style which has been set for it in the original layout (e.g. rounded corner, border width, colour etc).

Seeking advice on this. Thanks!

How to remove message event handler in javascript. Event not closing and duplicating

I am creating a script for a custom menu with clickable buttons that can be used for either opening new windows with new buttons, or placing functions behind buttons for playing music in game ect.

The problem I am facing is that whenever you close the menu by clicking on the “Close” button, and open the menu again, the even is executed twice. When you repeat this, it happens 4 times, then 8 and so on. It seems that it “addEventHandler” is not closed and when the menu is opened again, a new handler is created. Now we have all these events running, and doing the same thing duplicating everything.

This is the code from Javascript.

window.addEventListener('message', function(event) {

  MenuName = event.data.MenuName
  MenuTitle = event.data.MenuTitle
  MenuOptions = event.data.MenuOptions

  if (MenuName == 'MainMenu') {
    $('#npc-header').html(MenuTitle);
    for (let i = 0; i < MenuOptions.length; i++) {
      if (i <= 6) {
        $("#option" + i).show();
        $("#option" + i).html(MenuOptions[i].Title);
        $(document).on('click', "#option" + i, function() {
          if (MenuOptions[i].Type == 'Menu') {
            if (MenuOptions[i].Title == 'Settings') {
              $.post('https://DokusCore--Menu/OpenSettingsMenu', JSON.stringify({}));
            };
            if (MenuOptions[i].Title == 'Functions') {
              $.post('https://DokusCore--Menu/OpenFunctionsMenu', JSON.stringify({}));;
            };
            if (MenuOptions[i].Title == 'Music') {
              $.post('https://DokusCore--Menu/OpenMusicMenu', JSON.stringify({}));;
            };
          } else if (MenuOptions[i].Type == 'Option') {
            if (MenuOptions[i].Title == 'Open Inventory') {
              $.post('https://DokusCore--Menu/Close', JSON.stringify({}));
              $('body').fadeOut();
              $.post('https://DokusCore--Menu/OpenInventory', JSON.stringify({}));
            };
          };
        });
      };

      if (i < 6) {
        for (let i = MenuOptions.length; i < 6; i++) {
          $("#option" + i).hide();
        };
      };
    };
  };

  if (MenuName == 'SettingsMenu') {
    $('#npc-header').html(MenuTitle);
    for (let i = 0; i < MenuOptions.length; i++) {
      if (i <= 6) {
        $("#option" + i).show();
        $("#option" + i).html(MenuOptions[i].Title);
        $(document).on('click', "#option" + i, function() {
          if (MenuOptions[i].Type == 'Menu') {

          } else if (MenuOptions[i].Type == 'Option') {

            if (MenuOptions[i].Title == 'Toggle Music') {
              $.post('https://DokusCore--Menu/ToggleMusic', JSON.stringify({}));
            };

          };
        });
      };

      if (i < 6) {
        for (let i = MenuOptions.length; i < 6; i++) {
          $("#option" + i).hide();
        };
      };
    };
  };


  $('body').fadeIn();
});

// Close the menu
$(document).on('click', ".btn-closeinterface", function() {
  $('body').fadeOut();
  $.post('https://DokusCore--Menu/Close', JSON.stringify({}));
});

Anyone an idea how to close this event whenever the user clicks on the close button ?

Many thanks in advance!

How to append non numbers in a tag, and clear the binded element in svelte

I am building a calculator app and need to append numbers to a display. I also need to either append a non-number like * /, or clear the display and use a function to do that. Both don’t work because I can’t clear the display or append non-numbers to the display. Thanks in advance!

Heres part of my code-

<script> let displayobj = 0; </script>

Then having

<p  id ="display" bind:this={displayobj}></p> 

In the display
It works for numbers like this
<button class="button" on:click={displayobj.append(9)}>9 </button>

But It doesn’t work for non numbers like* / – + symbols, and gives me a red line when i do this
<button class="button" on:click={displayobj.append(*)}>*</button>

Also when I try to clear the number like this

<button class="button" on:click={displayobj = 0}>Clear</button>

It doesn’t work and freezes
my code so I can’t append anything anymore.

So I tried to have a function do it like this

<button class="button" on:click={clear}>Clear</button>

Then having this

<script> function clear(){ displayobj = 0; }</script>

But that didn’t work either can you tell me why? Thank you!

Making an AJAX request to an API endpoint directly (without webserver)

We create MWEs as part of our job descriptions when hiring freelancers and our current one requires launching a python API through a simple shell script and opening a simple index.html file in the browser. We can get around the CORS issue(s) by disabling web security on browser launch. However, we can’t seem to get the browser to accept the AJAX call (see below for more details). Is it possible to configure the call so it uses 127.0.0.1 or maybe localhost? Asking our freelancers to set up webservers and/or to port forward their routers would scare many of them away.

AJAX Call:

await $.ajax({
    type: 'POST',
    url: 'http://127.0.0.1/health'
});

How to send Base64 from front-end to API

I am attempting to send a fax with the Vitelity API. I have an API on EC2 that I am calling from the front-end of my React Native app, and that in turn calls the Vitelity API:

const Base64String = async (req, res) => {
  let body = req.body;
  await postFax(body);
  return res.status(200).send({
    statusCode: 200,
    data: {
      ...body,
    },
  });
};

const postFax = async ({
  login,
  pass,
  faxnum,
  faxsrc,
  recname,
  file1,
  data1,
}) => {
  const VITELITY_URL = `https://api.vitelity.net/fax.php?login=${login}&pass=${pass}&cmd=sendfax&faxnum=${faxnum}&faxsrc=${faxsrc}&recname=${recname}&file1=${file1}&data1=${data1}`;

  await fetch(VITELITY_URL, {
    method: "POST",
  })
    .then((res) => res.text())
    .then((result) => {
      console.log(result);
    })
    .catch((err) => console.log(err));
};

data1 is Base64 encoded and works with a test image I have that is ~24k characters, however some of the images I’m taking have been upwards of 1.2m characters.

The exact issue I’m getting is 414 Request-URI Too Large.

This is the front-end:

const sendB64 = b64 => {
    let formdata = new FormData();
    formdata.append('login', testLogin);
    formdata.append('pass', testPass);
    formdata.append('cmd', 'sendfax');
    formdata.append('faxnum', destinationNumber);
    formdata.append('faxsrc', testSenderNumber);
    formdata.append('recname', 'Test');
    formdata.append('file1', 'testfax.jpg');
    formdata.append('data1', b64);

    let requestOptions = {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      body: formdata,
      redirect: 'follow',
    };

    fetch(API_URL, requestOptions)
      .then(response => response.json())
      .then(result => {
        console.log(result);
        showMessage({message: `status: ${result.statusCode}`});
      })
      .catch(error => console.log('error', error));
  };

Javascript event check if events were triggered by the same user action

I want to check if two different events were triggered by the same user action.
For example, I have a “keydown” event listener and a “beforeinput” event listener with an editable div.
Is there a way I can check if both events were triggered by the same key press?
I know I could do it in a hacky way checking the time between the events, but is there a reliable/deterministic way to know if the events were triggered by the same input from the user?

If not a specific property, is there maybe a more reliable way to increment an id number after each event loop or push a callback to the end of the stack after the event loop to know the events on the stack would have all needed to be added at the same time by the same user input before the user would have been able to press another key or do another action?

Why does the setState fn needs to be called through another function?

Lets look at the code below

import React from "react"

export default function App() {
    const [isGoingOut, setGoingOut] = React.useState(false);
    
    function yeet() {
        setGoingOut(prevValue => prevValue ? false : true);    
    }
    
    return (
        <div className="state">
            <h1 className="state--title">Do I feel like going out tonight?</h1>
            <div className="state--value" onClick={yeet}>
                <h1>{isGoingOut ? "Yes" : "No"}</h1>
            </div>
        </div>
    )
}

I’m calling the set function setGoingOut() through the function yeet(). However, if I directly call the setGoingOut() function as below

import React from "react"

export default function App() {
    const [isGoingOut, setGoingOut] = React.useState(false);
    
    setGoingOut(prevValue => prevValue ? false : true);
    
    return (
        <div className="state">
            <h1 className="state--title">Do I feel like going out tonight?</h1>
            <div className="state--value" onClick={setGoingOut}>
                <h1>{isGoingOut ? "Yes" : "No"}</h1>
            </div>
        </div>
    )
}

it throws an error. Is this related to the React philosophy of not letting the state be changed directly (the same reason we can’t change a state variable count as count++ but have to do count + 1?