Categories
JavaScript Answers

How to access JSON data loaded in a script tag with src set with JavaScript?

If you load JSON data using a <script> tag with the src attribute pointing to a JSON file or a JSONP endpoint, we can access the loaded data using JavaScript.

To do this, we:

Assuming you have a JSON file named data.json with the following content:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}
  1. In your HTML file, load the JSON data using a <script> tag with the src attribute pointing to the JSON file:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Access JSON Data</title>
</head>
<body>
  <script src="data.json"></script>
  <script src="script.js"></script>
</body>
</html>
  1. In your JavaScript file (script.js), access the loaded JSON data:
// Access the global variable that holds the JSON data
console.log(jsonData);

// Access specific properties
console.log('Name:', jsonData.name);
console.log('Age:', jsonData.age);
console.log('City:', jsonData.city);

This assumes that the JSON file is structured as an object, and it will be loaded into a global variable named jsonData.

After the script tag with the JSON file is executed, you can access the JSON data in your JavaScript code just like you would access any other JavaScript object.

Note: Make sure that the server hosting the JSON file allows CORS (Cross-Origin Resource Sharing) if the HTML file is hosted on a different domain. Otherwise, you might encounter CORS errors.

Categories
JavaScript Answers

How to add an input field to accept only numbers with Angular and TypeScript?

To create an input field that accepts only numbers in an Angular application using TypeScript, you can utilize Angular’s built-in forms and validators.

To do this, we:

  1. Create a Reactive Form: First, create a reactive form in your Angular component.

  2. Add FormControl for the Input Field: Add a FormControl to represent the input field in the form.

  3. Apply Validators: Apply a custom validator to the FormControl to ensure it only accepts numeric values.

For example, we follow:

  1. In your component HTML file (app.component.html), add an input field within a form group:
<form [formGroup]="numberForm">
  <input type="text" formControlName="numericInput">
</form>
  1. In your component TypeScript file (app.component.ts), create the form and add validators:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  numberForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.numberForm = this.formBuilder.group({
      numericInput: ['', [Validators.required, this.onlyNumbersValidator]]
    });
  }

  // Custom validator function to allow only numbers
  onlyNumbersValidator(control) {
    if (isNaN(control.value)) {
      return { onlyNumbers: true };
    }
    return null;
  }
}

In this code, we import necessary Angular modules for forms.

Then we defines a form group (numberForm) in the component class.

In the ngOnInit lifecycle hook, creates the form group and adds a FormControl (numericInput) with the custom validator onlyNumbersValidator.

Next we define a custom validator function onlyNumbersValidator that checks if the input value is not a number.

If it’s not a number, it returns an object indicating validation failure; otherwise, it returns null.

With this setup, your input field will only accept numeric values, and an error will be displayed if a non-numeric value is entered.

Categories
JavaScript Answers

How to scale an image to fit on canvas with JavaScript?

To scale an image to fit onto a canvas with JavaScript, you need to calculate the appropriate scaling factor and then draw the image onto the canvas with the desired dimensions.

For example we write:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scale Image to Fit Canvas</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="300"></canvas>
    <script>
        // Get the canvas element and its context
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // Create an image element
        var img = new Image();
        img.src = 'your_image_url_here.jpg'; // Replace 'your_image_url_here.jpg' with the URL of your image

        // When the image is loaded, scale and draw it on the canvas
        img.onload = function() {
            // Calculate the scaling factors to fit the image onto the canvas
            var scaleX = canvas.width / img.width;
            var scaleY = canvas.height / img.height;
            var scale = Math.min(scaleX, scaleY); // Use the smaller scale factor

            // Calculate the new dimensions of the image
            var scaledWidth = img.width * scale;
            var scaledHeight = img.height * scale;

            // Calculate the position to center the image on the canvas
            var x = (canvas.width - scaledWidth) / 2;
            var y = (canvas.height - scaledHeight) / 2;

            // Clear the canvas and draw the scaled image
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, x, y, scaledWidth, scaledHeight);
        };
    </script>
</body>
</html>

In this code, we load the image using the Image constructor.

When the image is loaded, calculate the scaling factors (scaleX and scaleY) to fit the image onto the canvas. Use the smaller scale factor to ensure the entire image fits within the canvas.

Next we calculate the new dimensions of the scaled image (scaledWidth and scaledHeight).

Then we calculate the position (x and y) to center the image on the canvas.

Finally, we clear the canvas and draw the scaled image using the drawImage method of the canvas context (ctx.drawImage).

Categories
JavaScript Answers

How to draw polygons on an HTML5 canvas with JavaScript?

Drawing polygons on an HTML5 canvas with JavaScript involves a few steps. Here’s a basic example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draw Polygons</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>
    <script>
        // Get the canvas element
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // Define a function to draw a polygon
        function drawPolygon(x, y, sides, radius) {
            ctx.beginPath();
            ctx.moveTo(x + radius * Math.cos(0), y + radius * Math.sin(0));

            for (var i = 1; i <= sides; i++) {
                ctx.lineTo(x + radius * Math.cos(i * 2 * Math.PI / sides),
                           y + radius * Math.sin(i * 2 * Math.PI / sides));
            }

            ctx.closePath();
            ctx.stroke();
        }

        // Example usage
        drawPolygon(200, 200, 6, 100); // Draw a hexagon at (200, 200) with a radius of 100
        drawPolygon(100, 100, 5, 50);  // Draw a pentagon at (100, 100) with a radius of 50
    </script>
</body>
</html>

This code defines an HTML page with a canvas element and JavaScript to draw polygons on it.

The drawPolygon function takes parameters for the position of the center (x and y), the number of sides, and the radius.

It then calculates the coordinates of each vertex of the polygon using trigonometry and draws lines between them using the canvas context’s lineTo method.

Finally, it closes the path and strokes it to draw the polygon.

Categories
JavaScript Answers

How to fix FormData entries not showing in console with JavaScript?

If FormData entries are not showing in the console, it’s likely because you’re trying to log the FormData object directly.

The FormData object is not a simple JavaScript object, so logging it directly won’t display its contents in the console.

Instead, you need to iterate over its entries and log each entry individually.

For instance we write:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Logging FormData Entries</title>
</head>
<body>

  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
    <br>
    <input type="submit" value="Submit">
  </form>

  <script>
    document.getElementById("myForm").addEventListener("submit", function(event) {
      event.preventDefault(); // Prevent form submission

      var formData = new FormData(this);

      // Log FormData entries
      for (var pair of formData.entries()) {
        console.log(pair[0] + ": " + pair[1]);
      }
    });
  </script>

</body>
</html>

In this example, when the form is submitted, a new FormData object is created from the form.

Then, a for…of loop is used to iterate over the entries of the FormData object.

Each entry is an array [key, value], where pair[0] represents the key (name of the form field) and pair[1] represents the value (value of the form field).

These key-value pairs are logged to the console individually.

This way, you can see the contents of the FormData object in the console.