Generate Random Abstract Backgrounds Using Vanilla JavaScript

Category: Javascript | January 21, 2022
Author:Aryan Tayal
Views Total:429 views
Official Page:Go to website
Last Update:January 21, 2022
License:MIT

Preview:

Generate Random Abstract Backgrounds Using Vanilla JavaScript

Description:

Today we’re going to be using plain JavaScript and CSS to create some really cool abstract backgrounds.

These are the kind of images you can use in place of the background on your website or blog.

How to use it:

1. Create an empty container in which you want to generate random abstract backgrounds.

<div class="bg"></div>

2. The main function for the abstract background generator.

const generateBoxes = (limit, parent) => {
  parent.innerHTML = "";
  // override colors here
  const colors = [
    "#577590",
    "#43aa8b",
    "#90be6d",
    "#f9c74f",
    "#f8961e",
    "#f3722c",
    "#f94144"
  ];
  for (i = 0; i < limit; i++) {
    let box = document.createElement("div");
    box.classList.add("box");
    box.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    box.style.height = `${Math.floor(Math.random() * 300 + 50)}px`;
    box.style.width = `${Math.floor(Math.random() * 300 + 50)}px`;
    box.style.top = `${Math.floor(Math.random() * 80)}%`;
    box.style.left = `${Math.floor(Math.random() * 80)}%`;
    parent.appendChild(box);
  }
};

3. Generate random abstract backgrounds and determine how many color boxes to generate.

generateBoxes(20, document.querySelector(".bg"));

You Might Be Interested In:


Leave a Reply