JavaScript Loading Spinner

JavaScript Loading Spinner
Code Snippet:p5.js Loading Spinner
Author: mrwolferinc
Published: May 5, 2024
Last Updated: May 5, 2024
Downloads: 73
License: MIT
Edit Code online: View on CodePen
Read More

This code helps you to create a loading spinner in JavaScript. It displays a spinning animation on a webpage. The spinner rotates indefinitely, indicating loading progress. It helps users visualize ongoing processes on the webpage.

You can use this code on websites to enhance user experience during loading times. It provides a visual cue that something is happening, reducing user frustration. Additionally, it adds a modern touch to your website’s design.

How to Create JavaScript Loading Spinner

1. First, load the following meta charset into the head tag of your HTML document.

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

2. Now, create a basic HTML file with a <canvas> element. This is where the spinner animation will be displayed. Ensure the <canvas> element covers the entire width and height of the webpage.

<main></main>

3. Apply some basic CSS to the <html> and <body> elements to ensure they cover the entire viewport without any scrolling. Additionally, set the <canvas> element to display: block; to ensure it fills its container properly.

html, body {
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}

4. Load the following Ajax CDN link before closing the body tag:

<script src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js'></script>

5. Define variables for spinner size, speed, and color at the beginning of your JavaScript code. Then, create a setup() function to initialize the canvas and set the spinner color. Inside the draw() function, use trigonometry to calculate the spinner rotation angle based on the frame count. Draw the spinner using the calculated angle and specified parameters.

let spinnerSize = 192;
let spinnerSpeed = 10;
let spinnerColor;

function setup() {
  createCanvas(windowWidth, windowHeight);
  spinnerColor = color(33, 150, 243);
}

function draw() {
  background(255);
  
  let step = frameCount % (spinnerSpeed * 7.25);
  let angle = map(step, 0, spinnerSpeed * 7.25, 0, TWO_PI);
  
  push();
  translate(width / 2, height / 2);
  rotate(angle);
  noFill();
  stroke(spinnerColor);
  strokeWeight(spinnerSize / 10);
  strokeCap(SQUARE);
  arc(0, 0, spinnerSize - (spinnerSize / 20), spinnerSize - (spinnerSize / 20), 0, PI + HALF_PI, OPEN);
  pop();
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

That’s all! hopefully, you have successfully created Javascript Loading Spinner. If you have any questions or suggestions, feel free to comment below.

Leave a Comment