Flood fill for html5 canvas not working as expected

I have a flood fill I’m using from another post on here.
I removed all the alpha channels but the colors are off.
I’v racked my brain for days changing things around and using different fill methods but this one has gotten me closest. I’ll be having users draw and fill as they please. Sorry if this is something simple.


<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey"></canvas>

<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

ctx.strokeStyle = "rgb(252, 53, 3)";
ctx.strokeRect(10, 10, 50, 50);
var red = [3, 252, 3];
floodFill(ctx, 15, 15, red);

ctx.strokeStyle = "rgb(3, 252, 3)";
ctx.strokeRect(75, 10, 50, 50);
var green = [3, 252, 3];
floodFill(ctx, 80, 15, green);

ctx.strokeStyle = "rgb(3, 119, 252)";
ctx.strokeRect(150, 10, 50, 50);
var blue = [3, 119, 252];
floodFill(ctx, 155, 15, blue);

ctx.strokeStyle = "rgb(0, 0, 0)";
ctx.strokeRect(225, 10, 50, 50);
var black = [0, 0, 0];
//floodFill(ctx, 230, 15, black);
//black get's stackoverflow and crashes page


function getPixel(imageData, x, y) {
  if (x < 0 || y < 0 || x >= imageData.width || y >= imageData.height) {
    return [-1, -1, -1, -1];  // impossible color
  } else {
    const offset = (y * imageData.width + x) * 4;
    var pixel = imageData.data.slice(offset, offset + 4); 
    pixel[3] = 1; // ignore alpha
    return pixel;
  }
}

function setPixel(imageData, x, y, color) {
  const offset = (y * imageData.width + x) * 4;
  imageData.data[offset + 0] = color[0];
  imageData.data[offset + 1] = color[1];
  imageData.data[offset + 2] = color[2];
  imageData.data[offset + 3] = color[0];
}

function colorsMatch(a, b, rSq) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length !== b.length) return false;

  for (var i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

function floodFill(ctx, x, y, fillColor, range = 1) {
  // read the pixels in the canvas
  const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
  
  // flags for if we visited a pixel already
  const visited = new Uint8Array(imageData.width, imageData.height);
  
  // get the color we're filling
  const targetColor = getPixel(imageData, x, y);
  
  console.log("target: " + targetColor + "Fill: " + fillColor);

  // check we are actually filling a different color
  if (!colorsMatch(targetColor, fillColor)) {

    const rangeSq = range * range;
    const pixelsToCheck = [x, y];
    while (pixelsToCheck.length > 0) {
      const y = pixelsToCheck.pop();
      const x = pixelsToCheck.pop();
      
      const currentColor = getPixel(imageData, x, y);

      if (!visited[y * imageData.width + x] && colorsMatch(currentColor, targetColor, rangeSq)) {

        setPixel(imageData, x, y, fillColor);
        visited[y * imageData.width + x] = 1;  // mark we were here already
        pixelsToCheck.push(x + 1, y);
        pixelsToCheck.push(x - 1, y);
        pixelsToCheck.push(x, y + 1);
        pixelsToCheck.push(x, y - 1);
      
      }
    }
    
    // put the data back
    ctx.putImageData(imageData, 0, 0);
  }
}
</script>

I don’t know what is causing the issue, if I try to pass in rgb value black (0,0,0) it crashes.

Formik submit button not triggered

I have a React form created with Formik & Yup and I have a little problem with the submit button.

The error message will be displayed if I try to click on an input field and leave.
If an error message is displayed and I click the “Save” button, all the error messages will disappear, instead of showing all my empty inputs.

This is my yup validation schema:

export const refillSchema = object({
date: date().required('Date is required'),
refillType: string().required('Refill type is required'),
kilometers: number().required('Kilometers is required').min(0, 'Kilometers must be at least 0'),
price: number().required('Price is required').min(0, 'Price must be at least 0'),
liters: number().required('Liters is required').min(0, 'Liters must be at least 0'),
kWh: number().required('KWh is required').min(0, 'KWh must be at least 0')
})

And this is my component:

import React from 'react';
import { ChevronLeftIcon } from '@heroicons/react/20/solid';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import { refillInitialValues } from '../../../utils/constants';
import { refillSchema } from '../../../utils/yupSchemas';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

export default function HandleFuelConsumption({ refill, electricVehicle, resetHandleVehicle }) 
{
return (
<div>
  <Formik
    initialValues={refill || refillInitialValues}
    validationSchema={refillSchema}
    onSubmit={(values, { resetForm }) => {
      const { date, kilometers, refillType, price, liters, kWh } = values;

      console.log(date, kilometers, refillType, price, liters, kWh);

      // Handle form submission
      // For example, you can make an API call or update the state

      resetForm(); // Reset the form after successful submission
    }}
  >
    {({ errors, touched, setFieldValue }) => (
      <Form>
        <div id="actionsBar" className="p-2 border-b-2">
          <div className="flex justify-between">
            <div className="flex items-center cursor-pointer text-[#3300FF]" onClick={resetHandleVehicle}>
              <ChevronLeftIcon className="w-[25px] h-auto" />
              <p>Back</p>
            </div>
            <button type="submit" className="flex items-center cursor-pointer text-white blue-button hover:opacity-80">
              <p>Save</p>
            </button>
          </div>
        </div>
        <div className="flex flex-wrap p-2 gap-x-6">
          <div>
            <label htmlFor="date" className="block text-sm font-medium text-gray-700">
              Date
            </label>
            <Field name="date">
              {({ field }) => (
                <DatePicker
                  id="date"
                  selected={field.value}
                  onChange={(date) => setFieldValue('date', date)}
                  className={`${
                    errors.date && touched.date ? 'border-red-500' : ''
                  } cursor-default block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-primary focus:outline-none focus:ring-primary-hover sm:text-sm`}
                  showTimeSelect
                  dateFormat="yyyy-MM-dd HH:mm:ss"
                  timeFormat="HH:mm:ss"
                />
              )}
            </Field>
            <ErrorMessage name="date" component="p" className="text-red-500 text-xs italic" />
          </div>
          <div>
            <label htmlFor="kilometers" className="block text-sm font-medium text-gray-700">
              Kilometers
            </label>
            <div className="mt-1">
              <Field
                id="kilometers"
                name="kilometers"
                type="number"
                min="0"
                className={`${
                  errors.kilometers && touched.kilometers ? 'border-red-500' : ''
                } block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-primary focus:outline-none focus:ring-primary-hover sm:text-sm`}
              />
            </div>
            <ErrorMessage name="kilometers" component="p" className="text-red-500 text-xs italic" />
          </div>
          <div>
            <label htmlFor="refillType" className="block text-sm font-medium text-gray-700">
              Refill Type
            </label>
            <Field
              as="select"
              id="refillType"
              name="refillType"
              className={`${
                errors.refillType && touched.refillType ? 'border-red-500' : ''
              } min-w-[100px] mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-primary focus:outline-none focus:ring-primary-hover sm:text-sm`}
            >
              <option value="Full">Full</option>
              <option value="Partial">Partial</option>
            </Field>
            <ErrorMessage name="refillType" component="p" className="text-red-500 text-xs italic" />
          </div>
        </div>
        <div className="flex flex-wrap p-2 gap-x-6">
          <div>
            <label htmlFor="price" className="block text-sm font-medium text-gray-700">
              Price
            </label>
            <div className="mt-1">
              <Field
                id="price"
                name="price"
                type="number"
                min="0"
                className={`${
                  errors.price && touched.price ? 'border-red-500' : ''
                } block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-primary focus:outline-none focus:ring-primary-hover sm:text-sm`}
              />
            </div>
            <ErrorMessage name="price" component="p" className="text-red-500 text-xs italic" />
          </div>
          {electricVehicle ? (
            <div>
              <label htmlFor="kWh" className="block text-sm font-medium text-gray-700">
                KWh
              </label>
              <div className="mt-1">
                <Field
                  id="kWh"
                  name="kWh"
                  type="number"
                  min="0"
                  className={`${
                    errors.kWh && touched.kWh ? 'border-red-500' : ''
                  } block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-primary focus:outline-none focus:ring-primary-hover sm:text-sm`}
                />
              </div>
              <ErrorMessage name="kWh" component="p" className="text-red-500 text-xs italic" />
            </div>
          ) : (
            <div>
              <label htmlFor="liters" className="block text-sm font-medium text-gray-700">
                Liters
              </label>
              <div className="mt-1">
                <Field
                  id="liters"
                  name="liters"
                  type="number"
                  min="0"
                  className={`${
                    errors.liters && touched.liters ? 'border-red-500' : ''
                  } block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-primary focus:outline-none focus:ring-primary-hover sm:text-sm`}
                />
              </div>
              <ErrorMessage name="liters" component="p" className="text-red-500 text-xs italic" />
            </div>
          )}
        </div>
      </Form>
    )}
  </Formik>
</div>
);
}

Rendering 3D .step files with javascript?

I’m looking for a way to render 3D models in JavaScript (React), specifically .step files made to ISO industrial standard witch are universal across cad platforms?

If someone knows the good library or solution to this problem please refer me to it.
Thanks in advance.

using regex with a variable to search a sentence

I am using the following regex to seach a sentence and want to match only values that are followed by a period. I am confused to why the following regex is true since the ta isnt followed by a period. How would I change it so doesnt match?


let text = 'Paracetamol takes up to an hour to work. to '

let regex = new RegExp("ta" + ".", "i")
console.log(regex.test(text))

How to access parameter list from application-level middlewares in express.js?

How to access the params in every incoming requests?

I got a middleware dedicated to checking if the record with recordId existed in my MongoDB database.
Now I wish every single request to go through this middleware with the inspiration from DRY. So I created an application-level middleware:
app.use(checkRecordsExistence)

The middleware checkRecordsExistence needs to access all param list in order to check the existence of relevant records and store them in req object for further use.

However req.params always returns {}. What is the way forward? I don’t want to add it in the router-level middlewares, because it is not clean, I worship DRY.

Here is my detailed implementation.

const checkRecordsExistence = asyncHandler(async (req, res, next) => {
    const { params } = req;
    for (const key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
            // Only check params corresponding to Object Id
            if (key.endsWith('Id')) {
                // Remove the "Id" suffix from the param name
                const modelNameLower = key.slice(0, -2);
                const modelName = modelNameLower.charAt(0).toUpperCase() + modelNameLower.slice(1);

                const Model = mongoose.model(modelName);
                const recordId = params[key];
                const record = await Model.findById(recordId);
                if (!record) {
                    return next(new ErrorResponse(
                        new Error(message.notFound(modelName)),
                        404
                    ));
                }
                // Attach the found record to the request object for further use
                // <=> req._class = await Class.findById(classId)
                req[`_${modelNameLower}`] = record;
                console.log(typeof(record));
            }
        }
    }
    next();
});

I can get it going well by putting the middleware in every single router-level route. But it is not clean.

Next.js 13.4.3: Website not updating after adding new posts on hosting, despite successful GET request to API

I am using next js 13.4.3 from app directory. I’m making a blog site, but I have a little problem. When I type npm run build locally on my computer and then npm run start, then after adding a new post to my headles cms(hygraph) and sending a GET request to my api, the page updates normally, new posts are shown. The problem starts when I upload my website to hosting, after adding a new post and sending a GET request to the api, the website does not update. I am sending the code below:

page.tsx:

import BlogCard from '@/components/blog/PostCard';
import styles from './blog.module.scss';

const hygraphContentApi = "URI HERE";

interface Post {
  title: string;
  createdAt: string;
  slug: string;
  shortDescription: string;
  author: {
    name: string;
    picture: {
      url: string;
    };
  };
  coverImage: {
    url: string;
  };
}

const QUERY = `
query {
  posts {
    title
    createdAt
    shortDescription
    slug
    author {
      name
      picture {
        url
      }
    }
    coverImage {
      url
    }
  }
}
`

export default async function Home() {
  const response: { data: { posts: Post[]}} = await fetch(hygraphContentApi, {
    
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: QUERY,
    })
  }).then(res => res.json())
  const posts = [...response.data.posts].sort((a, b) => {
    const dateA: Date = new Date(a.createdAt);
    const dateB: Date = new Date(b.createdAt);
    return dateB.getTime() - dateA.getTime();
  });
  return (
    <main>
      {posts ? (
        <div className={styles.blogCardsContainer}>
        {posts.length > 0 ? (
          posts.map((post) => (
            <BlogCard key={post.slug} post={JSON.stringify(post)} />
          ))
        ) : (
          null 
        )}
        </div>  
      ) : <div className={styles.loading}>Loading...</div>}
    </main>
  );
};

route.tsx (api):

import { revalidatePath } from "next/cache";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
  const url = new URL(req.url);
  const auth = url.searchParams.get('auth');
  const path = url.searchParams.get('path')
  if(!path) return NextResponse.json({revalidated: false}, {status: 400})
  if(!auth) return NextResponse.json({revalidated: false}, {status: 400})
  if(auth != process.env.HYGRAPH_WEBHOOK_REVALIDATE_AUTHID) return NextResponse.json({revalidated: false}, {status: 401})
  revalidatePath(path)
  return NextResponse.json({revalidated: true, message: 'OK'}, {status: 200})
}

After sending a get request on the hosting, I get a message that everything was successful.
I tried clearing the cache on the hosting, and re-deploying, but it didn’t help…

Python Gstreamer Webrtcbin does not rtsp video to javascript peer

Recently, I am working on streaming RTSP cameras to Javascript Webrtc peer to show the stream on the web.
The Project Will be run on local network.
I’ve tried to setup a connection similar to this gst-rtsp-webrtc github whic is based on centricular/gstwebrtc-demos

I am using django channels as signaling server and this is the scenario i do for this process:

  1. the javascript peer sends “new-peer” request to python gstreamer throgh websockets
  2. the gstreamer starts creating new offer and gathers ice candidates, ice candidates are saved in a list to be sent at next step
  3. the javascript peer receives the offer, then set remote description, creates the answer and sends it back, it also starts gathering ice candidates and sends it to gstreamer peer through websockets
  4. gstreamer receives the answer and set remote description
  5. the ice candidates are received and set, then the listed ice candidates are sent to javascript peer
  6. javascript peer set these ice candidates to peer connection

Both the Javascript and Gstreamer goes into Connected state(I am console logging and printing the states)

also the Gstreamer Pipeline starts Playing(this is the log from printing bus messages):

Pipeline state changed from null to ready.
MessageType Stream Status:  (type=<enum GST_STREAM_STATUS_TYPE_CREATE of type Gst.StreamStatusType>, owner=<__gi__.GstQueue object at 0x7f275ac9a280 (GstQueue at 0x11e4640)>)
-------------------------------------------------------
MessageType Stream Status:  (type=<enum GST_STREAM_STATUS_TYPE_CREATE of type Gst.StreamStatusType>, owner=<__gi__.GstQueue object at 0x7f275ac9ac00 (GstQueue at 0x11e4040)>)
-------------------------------------------------------
MessageType Progress:  (type=<enum GST_PROGRESS_TYPE_START of type Gst.ProgressType>, code='open', text='Opening Stream')
-------------------------------------------------------
Pipeline state changed from ready to paused.
-------------------------------------------------------
<flags GST_MESSAGE_NEW_CLOCK of type Gst.MessageType>
-------------------------------------------------------
MessageType Stream Status:  (type=<enum GST_STREAM_STATUS_TYPE_ENTER of type Gst.StreamStatusType>, owner=<__gi__.GstQueue object at 0x7f275ac9d280 (GstQueue at 0x11e4640)>)
-------------------------------------------------------
MessageType Stream Status:  (type=<enum GST_STREAM_STATUS_TYPE_ENTER of type Gst.StreamStatusType>, owner=<__gi__.GstQueue object at 0x7f275ac9d300 (GstQueue at 0x11e4040)>)
-------------------------------------------------------
MessageType Progress:  (type=<enum GST_PROGRESS_TYPE_START of type Gst.ProgressType>, code='request', text='Sending PLAY request')
Pipeline state changed from paused to playing.
-------------------------------------------------------
MessageType Progress:  (type=<enum GST_PROGRESS_TYPE_CONTINUE of type Gst.ProgressType>, code='connect', text='Connecting to rtsp://admin:[email protected]:554/cam/realmonitor?channel=1&subtype=1')
-------------------------------------------------------
MessageType Progress:  (type=<enum GST_PROGRESS_TYPE_CONTINUE of type Gst.ProgressType>, code='open', text='Retrieving server options')
-------------------------------------------------------
MessageType Progress:  (type=<enum GST_PROGRESS_TYPE_CONTINUE of type Gst.ProgressType>, code='open', text='Retrieving media info')
-------------------------------------------------------
MessageType Progress:  (type=<enum GST_PROGRESS_TYPE_CONTINUE of type Gst.ProgressType>, code='request', text='SETUP stream 0')
-------------------------------------------------------

The problem is that the javascript is just getting one track:


function addTrackToVideo(peer, cameraVideo){
    // var cameraStream = new MediaStream();
    // console.log('setting up the track listener');
    // cameraVideo.srcObject = cameraStream;
    peer.addEventListener('track', (event) => {
        console.log("Received Track...");

        // cameraStream.addTrack(event.track, cameraStream);
        if (cameraVideo.srcObject !== event.streams[0]) {
            console.log('Incoming stream', event.streams[0]);
            cameraVideo.srcObject = event.streams[0];
        }else {
            console.log('srcObjrct is the same');
        }
    })
}

this is the gstreamer pipe line:

PIPELINE_DESC = '''
webrtcbin name=sendrecv rtspsrc location={rtsp_src} name=demuxer demuxer. ! queue ! parsebin name=parsebin ! rtph264pay config-interval=-1 timestamp-offset=0 ! queue ! application/x-rtp,media=video,encoding-name=H264,payload=98 ! queue ! sendrecv.
'''

i can also display the rstp stream using both the VLC and another gstreamer pipeline

how to check if the webrtcbin is not sending or javascript is not receiving?
what are your guesses about this problem?

How to print login and signup details in a site using Admin button

I created a login form using html and css, i had created a Admin button when i click on the admin button it needs to print the logged in and signup persons details in a table format.

Iam learning java script, html and css. So i created a simple login form and then i created a admin buton.I decided to give a functionality to admin buton.

  1. When i logged in or signup i need to store that data
    2)I need to print the stored data when i clicked on admin button in tabular format.

How to use mustache notation within in a nodered ui template

My node-red UI template node starts with a script like this:

<script>
    (function($scope) {

later on in the script there is an if statement like this:

} else if ($scope.msg.topic === "temperature_avg") {
        
        high = 88;
        mid = 65;
        low = 60;
        size= "0.9em";
        }

Instead of having the variables hardcoded inside this script I want to pass them via msg.payload.ranges1 and have the if statement looking like this:

} else if ($scope.msg.topic === "temperature_avg") {
        
        {{msg.payload.ranges1}}
        }

But its not working.

Logout function throws cannot destructure property ‘token’ of ‘useSelector(…)’ as it is null after switching from localstorage to sessionStorage

This error comes up if I store the user in sessionStorage, but works well with localStorage. It says cannot destructure property ‘token’ of ‘useSelector(…)’ here:

Page

import { useSelector } from "react-redux";
import { Input } from "@chakra-ui/react";

const Page = () => {
const { token } = useSelector((state) => state.auth.user);

return (
  <Input value={token} />
)
}

Only thing I changed in authSlice is this:

const login = async (formData) => {

  if (response.data) {
    sessionStorage.setItem("user", JSON.stringify(response.data)); //localStorageStorage.removeItem("user");
  }
  return response.data;
};

const logout = async () => {

  if (response.data) {
    sessionStorage.removeItem("user"); //localStorageStorage.removeItem("user");
  }
  return response.data;
  
};

When I logout it throws this error. What could be the problem?

How can I make the hex square select rounded?

I have been writing a game via JavaScript, html, css, and php. It uses a grid of hexagons. Right now, I can get a highlight of a square of hexes. I’d really like to have a circle highlight. I tried one way and got a circle but it could only go up to size 5.

The code for the map highlighting follows:

map.php: draw the hex grid

<div id="main" class="seldiv">
    <div id="container">
        <?php
            $v=0;
            $s=0;

            for ($y=0; $y<=22; $y++) {
                for ($x=0; $x<=11; $x++) {
                    $dy=$y-11;
                    $dx=$x-$s;
                    $dz=-$dx-$dy;
                    /*
                    if ($x==0 && $y==0) {
                        echo "<div id='$v' name='$x,$y' value='$dx,$dy,$dz' class='space axis play'></div>nr";
                        $v++;
                    } else {
                        if ($y&1==1 && $x==11) {
                            //skip
                            $s++;
                        } else {
                            */
                            if ($dx==0 || $dy==0 || $dz==0) {
                                echo "<div id='$v' name='$x,$y' value='$dx,$dy,$dz' class='space axis'>$x,$y</div>n";
                                $v++;
                            } else {
                                echo "<div id='$v' name='$x,$y' value='$dx,$dy,$dz' class='space'>$x,$y</div>n";
                                $v++;
                            }
                        /*
                        }
                    }
                    */
                }
                echo "n<br />nn";
            }
        ?>
    </div>
</div>

map.css: make it look right

* {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor:default;
}
#gamecontent {
    border:1px solid #000000;
    background-color:#000000;
    position:fixed;
    color:#a6a6a6;
    top:11.5%;
    left:50%;
    border-radius:30px;
    transform:translateX(-50%);
    width:88%;
    height:86%;
    overflow:hidden;
    z-index:100;
    visibility:visible;
}
#main {
    border:0px solid steelblue;
    //background-color:rgb(5,5,5);
    color:#afafaf;
    position: fixed;
    top:0;
    left:50%;
    border-radius:30px;
    transform:translateX(-50%);
    width:100%;
    height:100%;
    overflow:hidden;
    border-bottom:none;
    visibility:visible;
    z-index:99999;
}
#container {
    --s: 26px;
    --m: 1.5px;
    --f: calc(1.732 * var(--s) + 12 * var(--m)  - 13px);

    position: relative;
    
    margin-left:auto;
    margin-right:auto;
    
    width:100%;
    height:100%;
    border:0px solid cyan;
    font-size: 0;
    z-index:300;
    overflow:hidden;
    padding:1%;
    padding-left:1.8%;
    padding-top:1.5%;
}
#container::before {
    content: "";
    width: calc(var(--s)/2 + var(--m));
    float: left;
    height: 110%;
    shape-outside: repeating-linear-gradient(
                       #0000 0 calc(var(--f) - 10px),
                       #000  0 var(--f));
}
.space {
    /* left:-6%; */
    transform:translateX(6%);
    text-align: center;
    line-height:20px;
    font-size:xx-small;
    width: var(--s);
    margin: var(--m);
    height: calc(var(--s)*1.1547);
    display: inline-block;
    clip-path: polygon(0% 25%, 0% 75%, 50% 100%, 100% 75%, 100% 25%, 50% 0%);
    background-color: rgba(69, 69, 69, 0.50);
    margin-bottom: calc(var(--m) - var(--s)*0.2885);
    z-index:300;
}

map.js: make it work

var spacetiles = document.getElementsByClassName("space");
var totaltiles=spacetiles.length;
var size=1;
var i=0;

var lrow=getrowlength(spacetiles);
var srow=lrow-1;

var highlightcolor="rgba(85,136,238,0.50)";
var spacecolor="rgba(85, 85, 85, 0.5)";

var ycount=size-1;

for (i = 0; i < totaltiles; i++) {
    spacetiles[i].addEventListener('click', function() {
        highlight(this,size);
    }, false);
}

function getrowlength(spacetiles) {
    var tilecount=0;
    while (parseInt(spacetiles[i].getAttribute("name").split(",")[1])<1) {
        tilecount=tilecount+1;
        i=i+1;
    }
    return tilecount;
}

function clearselect() {
    ycount=size;
    for (i = 0; i < this.totaltiles; i++) {
        if (this.spacetiles[i].classList.contains("space")) {
            this.spacetiles[i].style.backgroundColor=spacecolor;
        }
    }
}

function highlight(tile,size) {
    clearselect();
    
    var x=parseInt(tile.getAttribute("name").split(",")[0]);
    var y=parseInt(tile.getAttribute("name").split(",")[1]);
    var l=x-size;
    var r=x+size;
    var t=y-size;
    var b=y+size;
    
        for (i=l;i<=r;i++) {
            for (j=t;j<=b;j++) {
                if (document.getElementsByName(i+","+j)[0]!=null) {
                    document.getElementsByName(i+","+j)[0].style.backgroundColor=highlightcolor;
                }
            }
        }
    }

Codepen of working code: https://codepen.io/jimmycode83/pen/xxQVMYw

Right now, it selects in a square as said. Anyway to make the select honeycombed and pretty circular? I’m thinking that the second loop of the two needs to be altered.

I initially wanted to draw it from the center up and down. But I can’t figure it out. The line above is the number of the size. The center line is the size * 2 + 1. Then the size gets one removed. That sounds like a loop to me. But while the thoughts seem good, the implementation eludes me. Any help making the select round instead of square would be most appreciated! Thanks.

Error in React with endpoint that returns a string or null

I have a endpoint that check if a user exists in database. Receive a username and password and returns the username if the user exists or null if does not exist. This endpoint works fine (checked with postman)
The problem is that when i call this endpoint, i always get a error. The error is that can read the string because is not a json.
enter image description here

This is the React code when i do the fetch:
enter image description here
This code is called from a component jsx.

Thanks in advance.

I have tried returning a json and works fine. The problem is when the endpoint returns string or null. I need that the endpoint can return a string value.

parseArgs, throws type error exact same sample code in docs

import { parseArgs } from 'node:util'

const args = []

const options = {
  t: {
    type: "string"
  }
}

const { values, positionals } = parseArgs({ args, options })

This code taken from the example code in the documentation throws this:

src/main.ts:13:51 - error TS2322: Type '{ t: { type: string; }; }' is not assign
able to type 'ParseArgsOptionsConfig'.
  Property 't' is incompatible with index signature.
    Type '{ type: string; }' is not assignable to type 'ParseArgsOptionConfig'.
      Types of property 'type' are incompatible.
        Type 'string' is not assignable to type '"string" | "boolean"'.

13 const { values, positionals } = parseArgs({ args, options })
                                                     ~~~~~~~

What the hell does this mean?