How can i use three identical figures in fabric js canvas

I didnt understang how to create three figures with the same size, but difrent color.
help is needed in correctly putting the names of functions and other things, I myself do not know how to do it correctly.

HTML FILE it only needs to be edited in DIV CLASS=”BOX”

<!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>TEST</title>
  <link rel="stylesheet" href="index.css">
</head>
<body>
<div class="box">
  <div class="data_list">
    <div class="data_item rect" draggable="true" ondragstart="onDragstart('rect')"></div>
    <div class="data_item rectgreen" draggable="true" ondragstart="onDragstart('rect')"></div>
    <div class="data_item rectred" draggable="true" ondragstart="onDragstart('rect')"></div>
  </div>
  <canvas id="c" style="border: 2px solid #ccc;"></canvas>
</div>

<script src="fabric.js"></script>
<script src="index.js"></script>
</body>
</html>

CSS FILE it okay

 .box {
      display: flex;
    }
    .data_list {
      width: 100px;
      margin-left: 10px;
    }
    .data_item {
      width: 60px;
      height: 40px;
      border: 1px solid #ccc;
      margin-bottom: 10px;
    }
    .data_item {
      width: 60px;
      height: 40px;
      border: 1px solid #ccc;
      margin-bottom: 10px;
    }
    .data_item {
      width: 60px;
      height: 40px;
      border: 1px solid #ccc;
      margin-bottom: 10px;
    }

    

js file it is need to be edit at switch (currentType) and function create

   let currentElType = null 

  let canvas = null

  function initCanvas() {
    
    canvas = new fabric.Canvas('c', {
      width: 1000,
      height: 700
    })

    
 
    canvas.on('mouse:down', function (opt) {
      var evt = opt.e;
      if (evt.altKey === true) {
        this.isDragging = true
        this.lastPosX = evt.clientX
        this.lastPosY = evt.clientY
      }
    })

    canvas.on('mouse:move', function (opt) {
      if (this.isDragging) {
        var e = opt.e;
        var vpt = this.viewportTransform;
        vpt[4] += e.clientX - this.lastPosX
        vpt[5] += e.clientY - this.lastPosY
        this.requestRenderAll()
        this.lastPosX = e.clientX
        this.lastPosY = e.clientY
      }
    })

    canvas.on('mouse:up', function (opt) {
      this.setViewportTransform(this.viewportTransform)
      this.isDragging = false
    })


    
    canvas.on('mouse:wheel', opt => {
      const delta = opt.e.deltaY 
      let zoom = canvas.getZoom() 
      zoom *= 0.999 ** delta
      if (zoom > 20) zoom = 20 
      if (zoom < 0.01) zoom = 0.01 

  
      canvas.zoomToPoint(
        { 
          x: opt.e.offsetX,
          y: opt.e.offsetY
        },
        zoom 
      )
    })
  }

  initCanvas()

  function onDragstart(type) {
    currentType = type
  }

  canvas.on('drop', function(opt) {

   
    let offset = {
      left: canvas.getSelectionElement().getBoundingClientRect().left,
      top: canvas.getSelectionElement().getBoundingClientRect().top
    }

    let point = {
      x: opt.e.x - offset.left,
      y: opt.e.y - offset.top,
    }

    let pointerVpt = canvas.restorePointerVpt(point)

    switch (currentType) {
      case 'rect':
        createRect(pointerVpt.y, pointerVpt.x)
        break
      case 'rect':
        createRectGreen(pointerVpt.y, pointerVpt.x)
        break
      case 'rect':
        createRectRed(pointerVpt.y, pointerVpt.x)
        break
    }
    currentElType = null
  })

  function createRect(top, left) {
    canvas.add(new fabric.Rect({
      top,
      left,
      width: 60,
      height: 40,
      fill: 'blue'
    }))
  }
  function createRectGreen(top, left) {
    canvas.add(new fabric.Rect({
      top,
      left,
      width: 60,
      height: 40,
      fill: 'green'
    }))
  }
  function createRectRed(top, left) {
    canvas.add(new fabric.Rect({
      top,
      left,
      width: 60,
      height: 40,
      fill: 'red'
    }))
  }



 

I just try to make figures with the same title in js

Image is Chrome Extension not shown

I would like to create a Chrome extension, where I append stars to a webpage. I have created the manifest.json, content.js and style.css files. I can see the place of the image, but it is not shown. I have spent 5-6 hours debugging it, but nothing seems to work.

Here is my manifest.json:

{
  "name": "Random Stars",
  "version": "1.0",
  "description": "Randomly assigns stars",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": [
        "<all-urls>"
      ],
      "css": [
        "style.css"
      ],
      "js": [
        "content.js"
      ]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": [
        "star.png"
      ],
      "matches": [ "<all-urls>" ]
    }
  ]
}

content.js:

if (window.location.hostname === "<url>") {
  const companyNames = document.querySelectorAll('<selector>');

  companyNames.forEach(companyName => {
    const stars = Math.floor(Math.random() * 5) + 1;
    const starDiv = document.createElement('div');
    starDiv.classList.add('company-stars');
    // starDiv.style.backgroundImage = chrome.runtime.getURL("star.png");
    starDiv.style.width = `${stars * 20}px`;
    companyName.insertAdjacentElement('afterend', starDiv);
  });
}

style.css:

.company-stars {
    display: inline-block;
    width: 100px;
    height: 20px;
    background-image: url("star.png");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
    margin-left: 5px;
  }

I can see that stars are generated because the place of the image is there and the length of each div is different, but the image is not shown at all.

What I tried so far:

  • I was able to open the image in Chrome in an HTML file
  • I tried to transform styles from style.css to content.js, but it did not help
  • Use only the display property of the CSS, but it did not help either
  • I tried to get rid of the image URL from CSS and JS files (separately) – if I got rid of it in CSS, the place of the image wasn’t there while it was when commenting out the background-img in the JS file
  • I made sure star.png is in the same folder as content.js, manifest.json and style.css
  • I also receive Uncaught DOMException: Failed to read the 'cookie' property from 'Document': The document is sandboxed and lacks the 'allow-same-origin' flag but I don’t think that is the issue here

If someone has experience with this, could you please help me? Thank you!

Need help on web development [closed]

Can someone help me with my mini project on web development?I want to build a basic website which will be a single platform for various services. Like if any user wants to organise an event, requires different services. Based on event category my website should show the service providers. I know html, css and JavaScript. Programming languages Java,C. I need some guidance where to start etc. How to create back-end stuff.

I can create the appearance part. I need to know about managing service providers/sellers and users, cart etc

Using Splide arrows outside of splide

I’m building this bootstrap page (mobile view) which has a splide. for the design, it’s way easier to have the arrows outside of the splide itself rather than trying to move the arrows into position.
But as the arrows are outside of the splide, then they’re not working – and im not sure what events need to be triggered to get it to slide.

  • Note – while the site is mostly bootstrap 5, it also has some tailwinds classes like paddingmargins (you might notice this in the code)

Here’s what the page looks like;
enter image description here

<!--  Mobile Display start -->
            <div class="row d-md-none">
                <div class="col-12 bg-white">
                    <div class="row">
                        <div class="col-6">
                            <img class="" style="width:75%;" src="Assets/CEDA-Dots_1.png" alt="ceda_dots">
                        </div>
                        <div class="col-6">
                            <img class="-mt-4 mx-auto" style="height:75%;" src="Assets/Qotes.png" alt="quotes">
                        </div>
                        <div class="col-10 pl-4 pb-2 -mt-8">
                            <p class="text-2xl font-medium pl-5">CEDA Learning - delivering value for organisations and individuals</p>
                        </div>
                        <div class="col-3 ml-4" style="position:relative; height: 25px;">
                            <div class="splide__arrows">
                                <button class="splide__arrow splide__arrow--prev" style="background-color:#ffffff;" type="button" aria-controls="mobile-testim-carousel-track" aria-label="Go to last slide">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40">
                                        <path d="m15.5 0.932-4.3 4.38 14.5 14.6-14.5 14.5 4.3 4.4 14.6-14.6 4.4-4.3-4.4-4.4-14.6-14.6z"></path>
                                    </svg>
                                </button>
                                <button class="splide__arrow splide__arrow--next" style="background-color:#ffffff;" type="button" aria-controls="mobile-testim-carousel-track" aria-label="Next slide">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40">
                                        <path d="m15.5 0.932-4.3 4.38 14.5 14.6-14.5 14.5 4.3 4.4 14.6-14.6 4.4-4.3-4.4-4.4-14.6-14.6z"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-12 mt-4" style="background: linear-gradient(90deg, #ffffff 50%, #e11837 50%)">
                    <div class="row">
                        <div class="col-12">
                            <p>&nbsp;</p>
                        </div>
                        <div class="col-12">
                            <div class="splide ml:0" id="mobile-testim-carousel">
                                <div class="splide__track pt-4 pb-4">
                                    <ul class="splide__list">
                                        <li class="splide__slide splide_width">
                                            <div class="container">
                                                <div class="row p-2 bg-white">
                                                    <div class="col-2 p-0 pt-2">
                                                        <img src="Assets/Portrait/10_Portrait.png" class="w-20">
                                                    </div>
                                                    <div class="col-10 text-black text-base ps-2 pt-2">
                                                        <p class="text-sm font-bold">Anne Finlay | Manager Coordination </p>
                                                        <p class="text-sm font-medium">WA Dept. Primary industries & Regional Development</p>
                                                    </div>
                                                    <div class="col-12 pt-3">
                                                        <p class="text-xs font-normal">I’ve worked in the public sector, across several agencies, for over 25 years. During this time, I have had several touch points with economic concepts without any real understanding of the broader economics framework. This online course filled in those gaps for me in a way that sustained my interest and allowed me to incorporate the learning into my existing workload. While going through the course, I had many ‘aha’ moments which cumulated in solid foundation in economics concepts.</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </li>
                                        <li class="splide__slide splide_width">
                                            <div class="container">
                                                <div class="row p-2 bg-white">
                                                    <div class="col-2 p-0 pt-2">
                                                        <img src="Assets/Portrait/10_Portrait.png" class="w-20">
                                                    </div>
                                                    <div class="col-10 text-black text-base ps-2 pt-2">
                                                        <p class="text-sm font-bold">Anne Finlay | Manager Coordination </p>
                                                        <p class="text-sm font-medium">WA Dept. Primary industries & Regional Development</p>
                                                    </div>
                                                    <div class="col-12 pt-3">
                                                        <p class="text-xs font-normal">I’ve worked in the public sector, across several agencies, for over 25 years. During this time, I have had several touch points with economic concepts without any real understanding of the broader economics framework. This online course filled in those gaps for me in a way that sustained my interest and allowed me to incorporate the learning into my existing workload. While going through the course, I had many ‘aha’ moments which cumulated in solid foundation in economics concepts.</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="col-12">
                            <p>&nbsp;</p>
                        </div>
                    </div>
                </div>
            </div>

and of course the JS:

<script>
new Splide('#mobile-testim-carousel', {type:'loop', arrows: false, rewind: true, pagination: false, autoplay: false, perPage: 1, gap:'1em'}).mount(); 
</script>

JavaScript comma separated links + Angular 10

I’ve an array of object and need to display comma seperated values as links

const arr = [
    {
        "processId": 1,
        "crIds": [
            {
                "crId": "10000112",
                "url": "https://test.metaverse.net/#/home?subTab=ceam_cm&request_id=10000112"
            },
            {
                "crId": "10000114",
                "url": "https://test.metaverse.net/#/home?subTab=ceam_cm&request_id=10000114"
            }
        ]
    },
    {
        "processId": 2,
        "crIds": [
            {
                "crId": "10000123",
                "url": "https://test.metaverse.net/#/home?subTab=ceam_cm&request_id=10000123"
            },
            {
                "crId": "10000999",
                "url": "https://test.metaverse.net/#/home?subTab=ceam_cm&request_id=10000999"
            }
        ]
    }
]
cont newArr = arr.map(crObj => {
     return '<a href="crObj.url" target="_blank" rel="noopener">'+ crObj.crId +'</a>' 
}).join(', )

I’m not sure how can we display comma separated link with text as crId and url as url

Why the series of one state variable is getting other state variable value in highcharts

Here, I have two state charts: Chart One and Chart Two. On the first click of the Chart One button, it renders the charts correctly. However, when I try to click on Chart Two, it doesn’t work. Instead, the Chart Two series receives values from Chart One. How can I avoid this issue?

Thank you.

Codesandbox link: https://codesandbox.io/s/fast-microservice-f0clmh?file=/src/Example.tsx

If I use a direct constant variable instead of state, the error disappears. However, I need to use state. Can anyone help me solve this?

Scroll-to-Top Behavior is not working in Next.js when Opening a New Page

In Next.js, I’m facing an issue where when I click on a link to open a new page, the new page opens at the same scroll position as the previous page. For example, if I’m on a product listing page and I have scrolled down to view the last product, when I click on that product, the product details page opens with the scroll position still at the bottom.

I would like the page to scroll to the top when opening the product details page. How can I achieve this scroll-to-top behavior in Next.js?

How can I close a Web Serial port

I want to close the serial port after a condition is met.

if (result !== null && i == 1) { 
            Swal.fire("error!", "", "error"); 
            port. close();
            break;
          } 

if (result2 !== null && i == 1) {
            Swal.fire("success!", "", "success");
            port. close();
            break;
          }

use port.close();
But the problem encountered is that the serial port cannot be close. and a warning message saying “Uncaught (in promise) TypeError: Failed to execute ‘close’ on ‘SerialPort’: Cannot cancel a locked stream
at connectSerial” How should I fix it? Thanks.

async function connectSerial() {
    const log = document.getElementById("target");
    try {
      const ports = await navigator.serial.getPorts();
      const port = ports[0];
      const bufferSize = 1024;
      await port.open({ baudRate: 115200, bufferSize });
      const decoder = new TextDecoderStream();
      const inputStream = decoder.readable;
      const reader = inputStream.getReader();
      port.readable.pipeTo(decoder.writable);

      let Number = $("#Number").val();
      $.ajax({
        url: "example.php",
        method: "POST",
        data: {
          Number: Number,
        },
        dataType: "json",
      })
        .done(async function (data) {
          console.log(data.hex);
          console.log(ascii_to_hexa(data.hex));
          let asciiVal = data.hex;
          const encoder = new TextEncoder();
          const writer = port.writable.getWriter();
          await writer.write(encoder.encode(asciiVal));
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          console.log("Ajax request failed: " + textStatus);
        });

      let i = 0;
      while (true) {
        const { value, done } = await reader.read();
        if (value) {
          log.textContent += value + "n";
          let text = value;
          let result = text.match("CN");
          let result2 = text.match("APPROVAL");
          if (result !== null && i == 1) {
            Swal.fire("error!", "", "error");
            port.close();
            break;
          }

          if (result2 !== null && i == 1) {
            Swal.fire("success!", "", "success");
            port.close();
            break;
          }
        }

        if (done) {
          console.log("[readLoop] DONE", done);
          reader.releaseLock();
          break;
        }
        i++;
      }
    } catch (error) {
      log.innerHTML = error;
    }
  }

Nextjs13 pass variable from page file to layout file

I want to set the layout conditionally on some pages its “FULL” and on others its “BlANK”. I need to pass variables from page to layout saying layout type BLANK or FULL.

and In the layout file, I am adding a layout depending on the variable.

But I cannot pass this variable to the layout file in nextjs13 is there a way to solve this problem? I tried “Home.layout = ‘Blank’;”, “getStaticProps”, and “getServerSideProps” but nothing helps.

Here is the code for that.
Page.js


export async function getServerSideProps() {
  return {
    props: {
      layout: "Blank"
    },
  };
}

// export async function getStaticProps() {
//   return { props: { layout: 'Blank' } }
// }


let Home = () => {
  return (
    <>      
        <SalesPoint />
    </>
  );
}

Home.layout = 'Blank';

export default Home; 

and in layout file


const layouts = {
  Blank: BlankLayout,
  Full: FullLayout,
};


export default function RootLayout(props) {
  console.log("pageProps", props); // see pageProps here

  console.log("RootLayout", JSON.stringify(props));

  const Layout = layouts[props.children.layout] || FullLayout;

  return (
    <html lang="en">
      <body className={`${kanit.variable} font-sans`}><Layout>{props.children}</Layout></body>
    </html>
  );
}

but not of this way working so can you suggest me the way to solve this problem?

On Scanning QR code getting “java.io.FileNotFoundException: SRVE0190E: File not found: /app/resources/locales/en-GB/components.mobile.json”

I am trying to get my mobile web application scan a QR code. On scanning the entire JSON is getting populated into one single field. It’s not getting parsed and populated properly.

On seeing the developer tools, I’m getting

Error 404: javax.servlet.ServletException:
java.io.FileNotFoundException: SRVE0190E: File not found:
/app/resources/locales/en-GB/components.mobile.json

And

Error 404: javax.servlet.ServletException:
java.io.FileNotFoundException: SRVE0190E: File not found:
/app/resources/locales/en/components.mobile.json

What is this? How to fix this?

Related question

update marker in google map from api response

I got stuck in a 3rd party API where I am getting users Lat long data every second by just calling the API once, it is keep giving users current Lat long data automatically, I want to integrate it using Laravel, JavaScript/jQuery but not getting any idea how to do it. Currently used ajax but due to continues data flow the API response keep getting load but not getting response however it is working in postman

TypeError: Cannot read properties of undefined (reading ’email’) – input type=”email”

I was trying to console.log data; first name, last name, email address. However, when the user submit the data, I can only console.log first name and last name and gave me a TypeError: Cannot read properties of undefined (reading ’email’) please see the code below and help clarify what was wrong with my code. Thank you so much.

The codes below are in my HTML file

  <body class="d-flex align-items-center py-4 bg-body-tertiary">
        <main class="form-signin w-100 m-auto">
        <form action="/" method="post">
            <div id="makeItCenter">
                <img class="mb-2" src="./images/IMG_2556.png" alt="" width="55%" height="55%">
            </div>
            <h1 id="makeItCenter" class="h4 mb-3 fw-normal">Signup to my Newsletter!</h1>
            
            <div class="form-floating">
            <input type="text" class="form-control mb-1" name="firstName" placeholder="First Name" required autofocus>
            <input type="text" class="form-control mb-1" name="lastName" placeholder="Last Name" required>
            <input type="email" name="email" class="form-control mb-1" placeholder="Email Address" required>
            </div>

            <button class="btn btn-primary w-100 py-2" type="submit">Sign Me Up!</button>
            <p id="makeItCenter" class="mt-2 mb-3 text-body-secondary">&copy; Trisha Supannopaj</p>
        </form>
        </main>

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
    </body>

The below codes are my app.js file

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const request = require("request");

app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static("public"));

const port = 3000;

app.get("/", function(req, res) {
    res.sendFile(__dirname + "/signup.html");
});

 app.post("/", function(req, res) {
    var firstName = req.body.firstName;
    var lastName = req.body.lastName;
    var emailAddress = res.body.email;
    console.log(firstName, lastName, emailAddress);
 })

app.listen(3000, function() {
    console.log(`This server is running on port ${port}!`);
})

API returned object is null for Mat-Autocomplete

I have written a code for Mat-autocomplete, where the values in the autocomplete are from an API.
This API returns in this format

[
    {
        "_id": "62bc7fcc3e184aac493ad519",
        "name": "Mike Austin",
        "email": "[email protected]",
        "role": "Account Manager"
    },
    {
        "_id": "62bc840a3e184aac493ad51b",
        "name": "Mitch Sawyer",
        "email": "[email protected]",
        "role": "Account Manager"
    }
]

I want to dispaly the name, while taking the internal value as _id.

My code goes something like this:

export interface AccountRepData {
    _id: string,
    name: string,
    email: string,
    role: string
}
wellForm: FormGroup;
accountReps: AccountRepData[];
filteredAccountReps: any[];
...
...

constructor(private fb: FormBuilder, private wellsTableService: WellsTableService) {
    this.wellForm = this.fb.group({
        accountRep: new FormControl('', Validators.required)
    });
}
ngOnInit(): void {
    this.products.clear()
    this.wellsTableService.getUsersByRole('Account Manager')
        .subscribe(response => {
            if (response.statusCode === 200 && response.status === 'SUCCESS') {
                this.accountReps = response.result;
                this.accountRepControl.valueChanges.pipe(
                    startWith(''),
                    map(value => this.filterAccountReps(value))
                ).subscribe(filteredAccountReps => {
                    this.filteredAccountReps = filteredAccountReps;
                });
            }
        });
}

filterAccountReps(value: string): any[] {
    const filterValue = value.toLowerCase();
    return this.accountReps.filter(accountRep => accountRep.name.toLowerCase().includes(filterValue));
}

get accountRepControl() {
    return this.wellForm.get('accountRep') as FormControl;
}

displayAccountRep(accountRep: any): string {
    if (accountRep) {
        const matchingAccountRep = this.accountReps.find(rep => rep._id === accountRep._id);
        if (matchingAccountRep) {
            return matchingAccountRep.name;
        }
    }
    return '';
}

And my html block is:

<mat-form-field class="full-width">
    <mat-label>Account Rep ID</mat-label>
        <input type="text" matInput placeholder="Account Rep ID" [formControl]="accountRepControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayAccountRep">
            <mat-option *ngFor="let accountRep of filteredAccountReps" [value]="accountRep._id">
                {{ accountRep.name }}
            </mat-option>
        </mat-autocomplete>
</mat-form-field>

For some reason in the displayAccountRep function the accountReps object is null. I think this might be a DOM issue, but I’ve been trying to figure this out for several hours and couldn’t find anything.

Any help would be greatly appreciated.

How can I make copy of value and store it to array?

I have calendar, If I click on day, I would like to make copy of this value and store it to Array, and if I click on another day, I would like to get current day copy and add it to array with prev day value. User can select multiple days. How can I do this? I am trying this way

const [dates, setDates] = useState([])
   console.log(dates)

   const handleClick = (e) => {
     e.preventDefault()

   const selectedDya = e.target.textContent
   console.log(selectedDya)
   setDates((prev) => ({...prev}, selectedDya))
   }


<section className='week'>
          {data[0][0].map((item, i) => (
              <span key={i}
                  onClick={handleClick}
                  className={'cell'}>
                {item}
             </span>
            ))}
        </section>

how to sort last 30 days to today in typescript

so i want to make a filter based on last 30 days till now.

code :

dataTtransaction: { dataTransactionOrder: [ { "dateTransaction": "04-04-2023 08:53:14" }, { "dateTransaction": "30-05-2023 08:53:14" }, { "dateTransaction": "01-06-2023 08:53:14" }]}
`

filterDate(param) {

let ends = new Date();
let starts = new Date(new Date().setDate(new Date().getDate() - 30));
let start = moment(starts).format('DD-MM-YYYY')
let end = moment(ends).format('DD-MM-YYYY')

this.prodFilter = this.dataTtransaction.dataTransactionOrder.filter( st => {
  let dates = moment(st.dateTransaction).format('DD-MM-YYYY')
  return (new Date(dates) >=  new Date(start) && new Date(dates) <= new Date(end))
});

}

`

so i want to make a filter based on last 30 days till now