How to crop canvas in percentages and crop 1 image to 2 or more smaller?

I’m stuck.
I have a code that allows you to enter the base64 code into the input and get, after pressing the button, the full image and the second image as part of the full image (cropped), but how can I get the third image as another cropped part of the whole? So the third image will be also cropped image but another part, not similar as first cropped. I have tried many options and none of them work.

Also, I have an additional question: can I crop by percentage? Let’s say I have an image of 500 by 500 pixels where in any of its area a circle of 100 by 100 pixels is displayed. Let’s say such an image is cropped to a triangle because I set it that way in the code. But if I upload the same image but smaller, 100 by 100 pixels, then there will be no triangle. So I need the crop in percentage.

<!DOCTYPE html>
<html>
    <head>
        <title>example</title>

        <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(document).ready(function () {
  $("#Base64_to_image_button").click(function () {
    document
      .getElementById("image_output")
      .setAttribute("src", $("#base64_input").val());
    $("#image_output").show();

    var canvasElement = document.createElement("canvas");
    var canvasContext = canvasElement.getContext("2d");
    var imageElement = document.querySelector("#image_output");
    imageElement.onload = function () {
      canvasContext.drawImage(
        imageElement,
        150, 180, 50, 50, 0, 0, 50, 50
      );
      var dataURL = canvasElement.toDataURL();
      var croppedImg = document.querySelector("#cropped-img");
      croppedImg.src = dataURL;
    };
    canvasElement.remove();
  });
});
</script>

    </head>

<body>
  <input id=base64_input value=""/>
  <button id=Base64_to_image_button>Go</button>
  <hr>
  <img id=image_output src="" alt="a">
  <hr>
  <img id=cropped-img src="" alt="b">

</body>
</html>

I can’t connect to localhost 5000, when I try to load the page, It says that It can’t access the site

I specify the port in .env file.
In the result I expect to see “{message:’WORKING!’}” on the page, but It just can’t open the page
There is a code in index.js

require('dotenv').config()
const express = require('express')
const models = require('./models/models')
const cors = require('cors')
const PORT = process.env.PORT || 5000

const app = express()
app.use(cors())
app.use(express.json)

app.get('/', () => {
   res.status(200).json({message:'WORKING!'})
})

const start = async () => {
   try {
      await sequelize.authenticate()
      await sequelize.sync()
      app.listen(PORT, () => console.log('Port ' + PORT))
   } catch (error) {
      console.log(error)
   }
}

start()

And in .env I have written PORT=5000

Angular Components are not Aligned

In my app, I have a tab. Inside this tab, there is a dropdown list and a button. I want to align these two components while aligning the dropdown to start and the button to end. I have tried the approach in my code yet, they are still not aligned as you can see. Also, I can not stretch the dropdown horizontally, it stays like the image below. What should I do to achieve what I want?

enter image description here

Code:

<div fxLayout.gt-xs="row" fxLayoutAlign="space-between end" fxLayout="column" class="m-8 mb-16">
    <div fxLayout="column" class="mt-16 mr-8" fxLayoutAlign="start center">
        <mat-form-field appearance="outline" fxFlex fxFlex.gt-sm="100" class="pr-4">
            <mat-label>Şube Kodu Seçimi</mat-label>
            <mat-select [(ngModel)]="this._materialPlan.StockBranch" name="StockBranch">
                <mat-option *ngFor="let dp of branchList" [value]="dp">
                    {{dp.BranchName}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </div>
    <div fxLayout="column" class="mt-16 mr-8" fxLayoutAlign="end center" style="margin-top: 200px;">
            <button mat-stroked-button [ngClass]="{'purple-fg': EditIndex==undefined}" [disabled]="EditIndex!=undefined"
            (click)="openProductSelectionDialog(); workItemForm.reset();">
            Yeni Ürün
        </button>
    </div>
</div>

Looping through data but wrong rendering on table

I have some nested data and i want to loop through them to show them in a table. But unfortunately the data is not appearing as expected. I want to create a row for each receiver with its corresponding data.
Can anyone tell me what am i doing wrong?

const projects = [
   {
     receivers:[
       {
         receiverName: "First",
         pages: [
            "Rules Page",
            "Login Page"
         ]
       },
       {
         receiverName: "Second",
         pages: [
            "Chat Page",
            "Main Page"
        ]
       }
     ],
     title: "Sever Issues",
     message: "Some of the Sever services will not be available during the day",
     type: "WARNING",
     startDate: "2022-04-18",
     endDate: "2023-04-30",
    },
    {
      receivers:[
        ....
    ]
  }
]

Table

  <thead>
    <tr>
     <th>#</th>
     <th>Project Name</th>
     <th>Page Name</th>
     <th>Notification Title</th>
     <th>Notification Message</th>
     <th>Notification Type</th>
     <th>Start Date</th>
     <th>End Date</th>
    </tr>
  </thead>
  {projects.map((project,key) => (
     <tbody key={key}>
       <tr><td rowSpan={project.receivers.length + 1}>{key}</td></tr>
       {project.receivers.map((p, key) => (
         <tr key={key}><td>{p.receiverName}</td></tr>
       ))}
       {project.receivers.map(n => (
         <tr><td>{n.pages}</td></tr>);
         ))}
       <tr key={key}>
         <td>{project.title}</td>
         <td>{project.message}</td>
         <td>{project.type}</td>
         <td>{project.startDate}</td>
         <td>{project.endDate}</td>
       </tr>
    </tbody>))}    

React JS to add Validation to individual input feild which are dynamically generated

I am working on react project and I have a button which will generate two dynamic inputs which will be key value pair. I want to validate them before user add one more field.

The validation will be, it should not be duplicate value and no special characters should be allowed. But the validation should appear below its individual field.

Stack blitz demo :https://stackblitz.com/edit/react-helloworld-gamgmo

Below is my code,


const App = () => {
  const [defaultTags, setDefaultTags] = useState({});
  const [formValues, setFormValues] = useState([{ name: '', email: '' }]);
  const [isEmpty, setIsEmpty] = useState(true);

  let handleChange = (i, e) => {
    let newFormValues = [...formValues];
    newFormValues[i][e.target.name] = e.target.value;
    setFormValues(newFormValues);
  };

  let addFormFields = () => {
    setFormValues([...formValues, { name: '', email: '' }]);
    setIsEmpty(true);


  // Some validation for feilds
  };

  validateAndAdd(){
  
 }
  let removeFormFields = (i) => {
    let newFormValues = [...formValues];
    newFormValues.splice(i, 1);
    setFormValues(newFormValues);
    setIsEmpty(false);
  };

  return (
    <>
      {formValues.map((element, index) => (
        <div className="form-inline" key={index}>
          <label>Name</label>
          <input
            type="text"
            name="name"
            value={element.name || ''}
            onChange={(e) => handleChange(index, e)}
          />
          <label>Email</label>
          <input
            type="text"
            name="email"
            value={element.email || ''}
            onChange={(e) => handleChange(index, e)}
          />
          {index ? (
            <button
              type="button"
              className="button remove"
              onClick={() => removeFormFields(index)}
            >
              Remove
            </button>
          ) : null}
        </div>
      ))}

      <div className="button-section">
        <button
          disabled={isEmpty}
          type="button"
          onClick={() => addFormFields()}
        >
          Add
        </button>
      </div>
    </>
  );
};

export default App;

Multiplying in javascript with textbox

I am a beginner javascript programmer. I made a very simple program to multiply 2 numbers with textbox. At first it worked. But then I wrote some logic to avoid some bugs. And some of the logics are not working. could anybody take a look at this code and tell me what’s wrong here:

let text1;
let text2;
let ans;

// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
    text1=document.getElementById('text1').value;
    text1 = Number(text1);
    text2=document.getElementById('text2').value;
    text2 = Number(text2);

    // checking if it is a number or not
    if(isNaN(text1)||isNaN(text2)){
        document.getElementById('P').innerHTML='it should be a number. Not alphabets or symbols';
    }

    // checking if it is an integer or not. 
    else if(text1.length>0 && Number.isInteger(text1)==false && text2.length>0 && Number.isInteger(text2)==false){
        document.getElementById('P').innerHTML='You cant multiply with decimal points';        
    }

    // checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
    else if(text1.length==0||text2.length==0){
        document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
    // else,  if it has no problem just multiply.
    else{
        let ans=BigInt(text1*text2);
        document.getElementById('P').innerHTML=ans;
        document.getElementById('zero').innerHTML='&times';
    }
}

I am getting the correct output when i enter the integer values in the text box and click submit button. But the problem is both the else if statement is not working. when i give the input as a float value it is not doing anything. It has to display the message , but it is not. same when i dont give any input and click the submit button. It is not displaying the message. Why does this happen. How to solve this?

HTML of this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>calculator</title>
    <link rel="stylesheet" href="calculator.css">
</head>
<body align="center">
    <input type="text" id="text1" placeholder="enter a value"> 
    <p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
    <br><br><br><p id="P"></p>
    <br><br><br><br><br><button id="mul">Multiply</button>
    <br><br><br><br><br><button id="sub">Subtract</button>
    <br><br><br><br><br><button id="div">Divide</button>
    <br><br><br><br><br><button id="add">Add</button>
    <script src="calculator.js"></script>
</body>
</html>

Invalid input focus is not working with FormArray

So everything works fine with normal FormGroup but when it comes to FormArray it doesn’t focus the invalid input.

My form initialization is below

initForm() {
    this.parentForm= this.fb.group({
      childFormArray: this.fb.array([this.createchildForm()])
    });
  }

after this, I initialize formarray like below

createChildForm(data?: any): FormGroup {
    var childForm = this.fb.group({
      name: [data?.name? data?.name: '']
    });
    childForm .valueChanges.subscribe(value => {
      var fieldWithValue = Object.keys(value).filter(key => value[key] == '');
      fieldWithValue.forEach(conName => {
         childForm .get(conName)?.addValidators([Validators.required]);
      });
    });
    return childForm ;
  }

My method to set errors after clicking submit (requirement);

   assignError(){
    this.parentForm.controls.childFormArray.value.forEach((v: any, index: number) => {
          var array = this.parentForm.controls.childFormArrayas FormArray;
          var item = array.at(index);
          var emptyItems = Object.keys(v).filter(key => v[key] == '');
          emptyItems.forEach(ele => {
            if (ele != "section") {
              item.get(ele)?.updateValueAndValidity({ emitEvent: false });
            }
          });
        });
       }

and after this I have made my validator which will check for invalid input and focus it.

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
    selector: '[focusInvalidInput]'
})
export class FormDirective {
    constructor(private el: ElementRef) { }
    @HostListener('submit')
    onFormSubmit() {
        const invalidControl = this.el.nativeElement.querySelector('.ng-invalid');
        if (invalidControl) {
            invalidControl.focus();
        }
    }
}

after this I have used its selector in my corresponding form

focusInvalidInput (ngSubmit)="saveDetails()"

and inside submit method I call my error adding method which is

 saveDetails(){
  assignError();
}

After doing all this I am able to focus invalid input but somehow its not working for formarray.

and when I console invalidControl its prints all the invalid input which should not happen maybe bcz there are many invalid input and whome should it focus so I tried using .first() method but it gives error saying first is not a method

Add element to mobile camera via JS

I have access to mobile camera from my web app. It works fine but the problem is when I want to push some div / overlay to camera view (it can be PNG image). User who will use it have to see some overlay on his camera view becauase the images have to be taken with a specific way.

The overlay will look like squere with empty space inside what will be look like person.

Is it solution for that?

Why can’t I access state object in my reduer in redux?

I can’t seem to figure out how to use redux.
I want to save an array of lists to the local storage and add a new list each time but I’m getting undefined for the lists variable.
………………………………………………………………….
This is my store

store.js

import { createStore, compose, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { listsReducer } from "./reducers/ListsReducer";

const initialState = {
    lists: localStorage.getItem('lists')
        ?JSON.parse(localStorage.getItem('lists'))
        :[]
}

const reducer = combineReducers({
    lists: listsReducer
});

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
    reducer,
    initialState,
    composeEnhancer(applyMiddleware(thunk))
);
export default store;

…………………………………………………………………
My reducer

ListsReducer.js

import { LISTS_ADD_LIST } from "../constants/ListsConstants";

export const listsReducer = (state = {lists:[]}, action) =>{
    switch(action.type){
        case LISTS_ADD_LIST:
             const list = action.payload;
             return {
                    ...state,
                    lists: [...state.lists, list]
             };
        default:
            return state;
   }
}

…………………………………………………………………
ListsConstants.js

export const LISTS_ADD_LIST = 'LISTS_ADD_LIST';

…………………………………………………………………
index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import App from './App';
import store from './store';

ReactDOM.render(
  <Provider store={store}>
  <React.StrictMode>
    <App />
  </React.StrictMode>
  </Provider>,
  document.getElementById('root')
);

……………………………………………………………………..
App.js

import {BrowserRouter} from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { addNewList } from "../actions/ListsActions";

function App() {
    const dispatch = useDispatch();
    const addList = ()=>{
        var date_time = new Date().toLocaleString();
        var title = 'my list '+date_time;

        var list = {
            _id:date_time,
            title:title,
            items:[]
        };
        dispatch(addNewList(list));
    }

    return(
         <div>
             <button onClick={addList}> </button>
         </div>
    );

}

……………………………………………………………………..
ListsActions.js

import { LISTS_ADD_LIST } from "../constants/ListsConstants";

export const addNewList = (list) => async(dispatch, getState) => {
    dispatch({
        type: LISTS_ADD_LIST,
        payload: list
    });
    localStorage.setItem('lists', JSON.stringify(getState().lists));
};

mobile number regex validation

”’

    function validate()
    var mob_num=document.getElementById("Mob_Number").value;
    var Mobilenumbercheck=/^[0-9]{10}$/;
    if(mob_num==''){
      document.getElementById('mobilenumbererror').innerHTML="Enter your Mobile Number";
    }
    else{
      if (mob_num!=''&& !Mobilenumbercheck.test('Mob_Number')){
      document.getElementById('mobilenumbererror').innerHTML="Invalid mobile number enter 
      valid number";
      return false;
      }
      else{
        return true;
      }
    } 

”’
HTML CODE:
”’

Mob Number

    <button type="submit" class="form-control" id="submit" name="submit" onclick="return 
    validate()">Add new </button>
    

”’

the code is not working as it is saving the details to the database. can someone please tell me where i am wrong as the condition is false it should give an error to the span tag but it isn’t.