html5 canvas scaling background grid problem

Hi I’m working on a HTML5 Canvas whiteboard.

Now I’m facing the problem, that the background grid looks weird if I zoom out.
Everything is stored in objects and I clear and redraw the stage on changes.

without scaling

with scaling

This is my grid class:

class Grid {
    constructor(
        x=0, y=0, width=0, height=0, scalesize=60
    ) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height; 
        this.scalesize = scalesize;
       
    }
    draw() {
        let {
            x,y,width, height,scalesize
        } = this;
        let distX = dx%60;
        let distY = dy%60;
        x -= distX;
        y -= distY;
     
        for(let i = x; i<canvas.width; i += scalesize)
        {
            ctx.beginPath();
            ctx.setLineDash([]);
            ctx.shadowColor='#00000000';
          
            ctx.moveTo(i,0);
            ctx.lineTo(i,canvas.height);

            ctx.strokeStyle= "#ccc";
            ctx.stroke();
        }
        for(let i = y; i<canvas.height; i += scalesize)
        {
            ctx.beginPath();
            ctx.setLineDash([]);
            ctx.shadowColor='#00000000';

            ctx.moveTo(0,i);
            ctx.lineTo(canvas.width,i);

            ctx.strokeStyle= "#ccc";
            ctx.stroke();
        }
       
    }
}

scaleSize is the size of each grid field. Currently it’s 60.

And this is my scale function:

// ----------------------------------------------
// scaling
// ----------------------------------------------
let scaleAmount = 1.00;
let scaleAnimation;
let animationReady = false;
let scalePercent =  parseInt(scaleSize.innerText.replace("%",""));

function scaleUpdate()
{
    
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.scale(scaleAmount, scaleAmount);   
   
    scaleSize.innerText = parseInt(parseFloat(scaleAmount.toFixed(1))*100)+"%";

    stageUpdate();  
   
}
function scale(direction)
{
    
    
    let targetScale ;

    if(direction=="zoomIn")
    { 
            targetScale = (scalePercent / 100) + 0.1;
            
            scaleAmount += 0.01;
        
            animationReady = scaleAmount > targetScale;
            targetScale= parseFloat(targetScale.toFixed(3));
            scaleAmount = parseFloat(scaleAmount.toFixed(3));
            dx += scaleAmount;
            dy += scaleAmount;   
    }
    if(direction=="zoomOut")
    {
            targetScale = (scalePercent / 100) - 0.1;
           
            scaleAmount -= 0.01;
           
            animationReady = scaleAmount < targetScale;
            targetScale= parseFloat(targetScale.toFixed(3));
            scaleAmount = parseFloat(scaleAmount.toFixed(3));
            dx -= scaleAmount;
            dy -= scaleAmount;
    }
 
    if (animationReady) {
        scaleAmount = targetScale;
        scalePercent =  parseInt(scaleSize.innerText.replace("%",""));
    } else {
        scaleAnimation = requestAnimationFrame(() => {
            scaleUpdate();
            scale(direction);
         });
    }
}

Tell me, if you need more infos.

I hope someone can help me to fix the problem.

Thanks in advance
Frank

Highcharts with Sharepoint Rest API

I am trying to create charts using Highcharts and Sharepoint Rest API. Essentially, I am using the code posted on Github here: https://github.com/Ramakrishnan-1/HighCharts-For-SharePoint-List-RESTAPI/blob/main/BuildHighCharts.js

The list I am using contains statuses of multiple tasks assigned to different users. It also contains a week column which is a calculated field.

It works fine to create a chart that distinguishes between Pending and Completed Items, but we would need a weekly overview of them, indicating how many items are Completed and Pending in each week. As a later addition, I would like to show only the trailing 4 or 8 weeks. The weeks that should be used are available in my Sharepoint list, and I am pulling that information using the Rest API. But I am getting stuck at counting these items for each week and then passing them over as data series to highcharts.

Has anyone experience with this and can give me a hint on how to realize it?

How to catch the error of Private field must be declared in an enclosing class?

I have this sample code:

class Person {
  #name = "Jack";
  static hasTitle(obj) {
    try {
      console.log(obj.#age);
    } catch (error) {
      console.log(Object.keys(error));
    }

    return #name in obj;
  }
}

const p = new Person();
console.log(Person.hasTitle(p));

And I want to catch the error that occurs because age is not defined on the Person object. What happens now is that the catch block is never reached, despite wrapping the faulty line with a try/catch block. So what is the problem here?

I’m perfectly aware of the in operator in case you’re wondering.

How to print the only the tbody of table html using javascript

jsfiddle link

<table border="1" cellpadding="3" id="printTable">
    <tbody id="printTbody"><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

<br />
<br />

<button onclick="printTablefun()">Print Table</button>
<button onclick="printtbodyfun()">Print Tbody</button>
<script>
function printTablefun()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}

function printtbodyfun()
{
   var divToPrint=document.getElementById("printTbody");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}
</script>

Description

  1. From this above link i have added the fiddle like and the code

Problem

  1. When i click the “Print Table” button its printing the properly as a table
  2. When i click the “Print Tbody” button its just printing only the text but in table format

What I needed

  1. When i click the “Print Tbody” button have to print the content in the tbody as in a table format

While clicking “Print Table” button

While clicking "Print Table" button

While clicking “Print Tbody” button

While clicking "Print Tbody" button

Why can you load a local Javascript file and not a local JSON or XML file? [duplicate]

  1. Javascript loads fine locally but not JSON. I understand it is a security issue, but confused about why a JSON file would potentially be more malicious than a Javascript file. I thought it would be the other way around?

  2. I can see that css, js and image files loads fine locally. Is it just JSON and XML that will not do this? Have not been able to find a list of what will and what will not work.

Getting ‘undefined’ from asynchronous response despite ‘await’ and ‘then’

I’m trying to send a GET request, parse its response and return it to another method. Apparently I have problems handling the asynchronous response.

I want to use Node.js’ standard modules, so no Axios.

// class 1: Calling API, processing and returning the response

export async function getData() {
  let str = '';

  const options = {
    hostname: 'jsonplaceholder.typicode.com',
    path: '/posts/',
    method: 'GET',
    json: true,
  };

  https
    .get(options, response => {
      response.on('data', chunk => {
        str += chunk;
      });

      response.on('end', () => {
        return parseJson(str);
      });
    })
    .on('error', error => {
      console.log(error);
    });
}

async function parseJson(str) {
  const json = JSON.parse(str);
  var text;
  try {
    json.forEach(element => {
      text += element.body;
    });
    // console.log(text); // I'm getting the expected output
    return text;
  } catch (error) {
    console.log('error');
  }
}


// class 2: Calling the 2 methods above

getData().then(function (value) {
  console.log('DATA: ' + value); // this is called first
});

Unfortunately as output I get an undefined. Despite using async and then:

DATA: undefined

How to scrape google images with unirest and cheerio?

I am trying to scrape google images by using unirest and cheerio, but I got stuck when I found that parsing was not happening correctly.
This is my code currently :

const unirest = require("unirest");
const cheerio = require("cheerio");


const getData = async() => {
    let count= [] , page_url = [];
    let url =
    "https://www.google.com/search?q=india&oq=india&tbm=isch&asearch=ichunk&async=_id:rg_s,_pms:s,_fmt:pc&sourceid=chrome&ie=UTF-8";
const response = await unirest
.get(
    url
)
.headers({
  "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36",
})
.proxy(
  "proxy"
);

const $ = cheerio.load(response.body)
console.log(response.body)//html file returned successsfully
let title = [] , link = [];
$(".vbC6V").each((i,el) => {
title[i] = $(el).find(".iKjWAf .mVDMnf").text()//not parsing
link[i] = $(el).find(".rg_l .rg_ic").attr("src")//not parsing
})
console.log(title)//returned empty
console.log(link)//returned empty
}

getData();

Why does is SVG not as “hot” as TEXT, when triggering click action for a theme change? (JavaScript/CSS/HTML)

Why does the SVG not as “hot” as the TEXT when triggering the action in this script?

All text elements fire the right theme nicely, BUT when these texts are replaced an SVG in the exact same button id location, the code does not select the corresponding theme.

It does however for the surrounding area of the SVG, but not the SVG itself.

I want to be able to use both the SVG itself and a little padding around the SVG for added ease of use.

<div id="scheme">
  <button id="auto">Auto</button>
  <button id="default">Default</button>
  <button id="light">Light</button>
  <button id="dark">Dark</button>
  <button id="blue">
    <svg width="20" height="20">
      <rect width="20" height="20" style="fill: lightgrey" />
      <!-- The face of this SVG does NOT actuate a theme change -->
    </svg>
  </button>
</div>

Demo

https://jsfiddle.net/eu097xsd/

localStorage doesn’t work in snippets here on Stack Overflow due to sandboxing so all the code in the snippet must be saved as a full page then tested in a real-world environment.
Also check out https://github.com/besworks/theme-selector

/* Besworks Hot Theme Without Memory Problems
https://github.com/besworks/theme-selector */

let prefersDark = matchMedia('(prefers-color-scheme: dark)');
prefersDark.addEventListener('change', event => loadTheme());

function setTheme(theme) {
  if (theme == 'auto') {
    localStorage.removeItem('theme');
    loadTheme(null);
  } else {
    localStorage.setItem('theme', theme);
    applyTheme(theme);
  }
}

function loadTheme(theme) {
  theme = localStorage.getItem('theme');
  theme ??= (prefersDark.matches) ? 'dark' : 'default';
  applyTheme(theme);
}

function applyTheme(theme) {
  document.documentElement.className = theme;
}

window.setTheme = setTheme;

loadTheme();



let selector = document.getElementById('scheme');
  selector.addEventListener('click', event => {
    if (event.target == selector) { return; }
    window.setTheme(event.target.id);
});
:root.default { --bgr: #eee; --txt: #000; }
:root.light { --bgr: #ddc; --txt: #446; }
:root.dark { --bgr: #222; --txt: #a75; }
:root.blue { --bgr: #246; --txt: #eec; }
body { background: var(--bgr); color: var(--txt); margin: 1.5rem; }

#scheme button {
border: 1px solid red;
background: none;
color: inherit;
text-decoration: underline;
cursor: pointer;
}
    <h1> Select a theme to change the color scheme! </h1>
    <div id="scheme">
        <button id="auto">Auto</button>
        <button id="default">Default</button>
        <button id="light">Light</button>
        <button id="dark">Dark</button>
        <button id="blue">
        <svg width="20" height="20">
            <rect width="20" height="20" style="fill: lightgrey; stroke-width:1px; stroke: red;" />
        </svg>
        </button>
    </div>

Add a subclass in d3 chart hierarchy

I was trying to add small triangle below tooltip and above bar.

For that I was following this document –
http://bl.ocks.org/caged/6476579

For tooltip , I have written below code –

var tip = d3Tip()
  .attr("class", "d3-tip")
  .style("line-height", 1)
  .style("font-weight", "bold")
  .style("padding", "12px")
  .style("background", "rgba(0, 0, 0, 0.8)")
  .style("color", "#fff")
  .style("border-radius", "2px")
  .attr("class", ":after")
  .style("box-sizing", "border-box")
  .style("display", "inline")
  .style("font-size", "10px")
  .style("width", "100%")
  .style("color", "rgba(0, 0, 0, 0.8)")
  .style("content", "\25BC")
  .style("position", "absolute")
  .style("text-align", "center")
  .offset([-10, 0])
  .html(function (_data, indexedData) {
    var htmlToolTip = "";
    keys.map((key, index) => {
      htmlToolTip +=
        "<strong>" +
        key +
        " : </strong> <span style='color:red'>" +
        indexedData.data[key + "Value"] +
        "</span> <br>";
    });
    return htmlToolTip;
  });

Here , I am trying to add below class properties-

/* Creates a small triangle extender for the tooltip */

.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "25BC";
  position: absolute;
  text-align: center;
}

But triangle not getting added below tooltip.

How can I use multiple refs for nested arrays of elements with hooks, or any other way

First of all, I’ve found the solution here, which works great with a single array of elements. But my question is regarding the nested arrays of components. For example:

const { useRef, useState, useEffect } = React;

const arr1 = [A, B, C]
const arr2 = [1, 2, 3]

const App = () => {
  const popoverRefs = useRef([]);

  return (
    <div>
      {arr1.map((parentItem, index) => {
        return(
          <div>
            A Parent Element {parentItem.label}
            {arr2.map((childItem, index2) => {
              return (
                <div ref={????}>
                  A Child Element {childItem.label}     
                </div>
              )
             })}
          </div>
        )
      })}
    </div>
  );
};

ReactDOM.render(
  <App />,
  document.getElementById("root")
);

In this example how can I use useRef or createRef to get the reference for each parent’s child separately, so that I can use those references to anchor some other view for example a popover.

How to use Jimp composite in Javascript to layer images

I’m trying to create in image generator where I can create all permutations of an image given different elements on 3 layers. I have managed to get the three folders into arrays and am trying to use Jimp to layer them on top of each other to create composite images. But I am failing to find the correct syntax to call the composite command in jimp.

const { jimpEvChange } = require('@jimp/core');
const { composite } = require('jimp');

CombineImagesFrom3Folders("Scenes/","Faces/","Features/");

function CombineImagesFrom3Folders(folder1, folder2, folder3) {
    var pngFiles1 = CreatePNGArrayFromFolder(folder1);
    var pngFiles2 = CreatePNGArrayFromFolder(folder2);
    var pngFiles3 = CreatePNGArrayFromFolder(folder3);
    DrawImagesOnTopOfEachOther(pngFiles1, pngFiles2,pngFiles3, "Combined/");
    
}

function CreatePNGArrayFromFolder(folder) {
    var pngFiles = [];
    var fs = require('fs');
    const newLocal = fs.readdirSync(folder);
    var files = newLocal;
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if (file.split(".").pop() == "png") {
            pngFiles.push(folder + "/" + file);
        }
    }
    return pngFiles;
}

function DrawImagesOnTopOfEachOther(pngs1, pngs2, pngs3, folder) {
    const jimp = require('jimp');
    var fs = require('fs');
    for (var i = 0; i < pngs1.length-1; i++) {
        for (var j = 0; j < pngs2.length-1; j++) {
            for(var k = 0; k < pngs3.length-1; k++){
                // compositing the images
                var image1 = jimp.read(pngs1[i]);
                var image2 = jimp.read(pngs2[j]);
                var image3 = jimp.read(pngs3[k]);
                image.composite(image1, image2, image3, (err, image) => {
                    if (err) throw err;
                    image.write(folder + "/" + i + j + k + ".png");
                }
                );
            }
        }
    }
}

I either get an error that “composite is not a function” or if I use “image.composite” then I get the error that “image is not defined”, if I define the image as something I get “image.composite is not a function”.

Hope someone can help.
James.

I am not able to use the router in react js

I have been trying to use a router on react project but getting an error :

A Route is only ever to be used as the child of Routes element, never rendered directly. Please wrap your Route in a Routes.

The Code Is Shown Below

import About from "./container/About";
import Profile from "./container/Profile";
import { useState } from "react";
import {BrowserRouter as Routes,Route} from 'react-router-dom'
function App(){
  const [state, setState] = useState('')
  return(
    <div className="App">
      <button onClick={()=>setState('about')}>About</button>
      <button onClick={()=>setState('profile')}>Profile</button>
      <Routes>
        <Route component={About} path='/about'></Route>
      </Routes>
    </div>
  )
}
export default App;

Loop over Go strings in Javascript inside Go template

Basically, what I want to do is add stuff inside script tags based on the number of words in a string in Go (loop).

I would also like to add script tags based on the string length but if you do that, it would throw an error.

Now I can’t access Go values inside script tags like this

var stringArray = {{.goArray}}
var stringValues = stringArray.split(",")

this actually ends up doing nothing.

<script>
var stringArray = "cat, bat, mat"  // <- SSR values, doesn't get assigned.
var stringValues = stringArray.split(",") // <- Doesn't work
</script>

I want to be able to use the string and run loops inside the script tag, something like this

<script> 
 for(let i = 0; i<stringValues; i++) {
   // do stuff
 }
</script>

How can i push array in matrix vertically?

const axaliGamoshveba = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],
  ];
  for (let i = 0; i < gamoshvebisMult.length; i++) {
    axaliGamoshveba[0].push(gamoshvebisMult[i].Soflis);
    axaliGamoshveba[1].push(gamoshvebisMult[i].Samto);
    axaliGamoshveba[2].push(gamoshvebisMult[i].Damamushavebeli);
    axaliGamoshveba[3].push(gamoshvebisMult[i].Eleqtroenergiis);
    axaliGamoshveba[4].push(gamoshvebisMult[i].Wyalbobarageba);
    axaliGamoshveba[5].push(gamoshvebisMult[i].Mshenebloba);
    axaliGamoshveba[6].push(gamoshvebisMult[i].Sabitumo);
    axaliGamoshveba[7].push(gamoshvebisMult[i].Transporti);
    axaliGamoshveba[8].push(gamoshvebisMult[i].Gantavsebis);
    axaliGamoshveba[9].push(gamoshvebisMult[i].Informacia);
    axaliGamoshveba[10].push(gamoshvebisMult[i].Safinanso);
    axaliGamoshveba[11].push(gamoshvebisMult[i].UdzraviQoneba);
    axaliGamoshveba[12].push(gamoshvebisMult[i].Profesiuli);
    axaliGamoshveba[13].push(gamoshvebisMult[i].Administraciuli);
    axaliGamoshveba[14].push(gamoshvebisMult[i].Saxelmwifo);
    axaliGamoshveba[15].push(gamoshvebisMult[i].Ganatleba);
    axaliGamoshveba[16].push(gamoshvebisMult[i].Jandacva);
    axaliGamoshveba[17].push(gamoshvebisMult[i].Xelovneba);
    axaliGamoshveba[18].push(gamoshvebisMult[i].Sxva);
    axaliGamoshveba[19].push(gamoshvebisMult[i].Shinameurneoba);
  }

I have my array from MySQL server and want to create matrix, but when I push my arrays like that, it adds horizontally.