I don't like doing homework for people, but then again getting past the technical stuff and being able to get creative and artistic is the fun part. So, here is a random square generator you can play with, and learn from. There are some comments to explain it more.

const canvas = document.getElementById("canv");
const ctx = canvas.getContext("2d");
const width = window.innerWidth;
const height = window.innerHeight;
const maxWH = Math.max(width, height);

//use resize event listener to change these on window resize...
canvas.width = width;
canvas.height = height;

//to generate random intergers from 0 to 255, for colour channels
function randomInteger(max = 256){
  return Math.floor(Math.random()*max);
}
//draw n squares at random places and sizes
function makeRandomSquares(n){
  for(let i = 0; i < n; i++){
    const size = Math.random()*(maxWH*0.15);
    //minus half the size from x,y
    //so they can overlap left and top of screen, not just bottom and right.
    const x = Math.random()*width-size/2;
    const y = Math.random()*height-size/2;
    //random rgba colour
    ctx.fillStyle = `rgba(${randomInteger()},${randomInteger()},${randomInteger()},${Math.random()*0.4})`;
    ctx.fillRect(x,y,size,size);
  }
}
//initialize with 2 squares
makeRandomSquares(2);
//make 2 more squares each click
document.addEventListener("click", function(){
  makeRandomSquares(2);
}, false);
html, body {
  margin: 0;
  padding: 0;
}
canvas {
  width: 100%;
  height: 100%;
}
<canvas id="canv"></canvas>

Answer from George on Stack Overflow
Top answer
1 of 3
4

I don't like doing homework for people, but then again getting past the technical stuff and being able to get creative and artistic is the fun part. So, here is a random square generator you can play with, and learn from. There are some comments to explain it more.

const canvas = document.getElementById("canv");
const ctx = canvas.getContext("2d");
const width = window.innerWidth;
const height = window.innerHeight;
const maxWH = Math.max(width, height);

//use resize event listener to change these on window resize...
canvas.width = width;
canvas.height = height;

//to generate random intergers from 0 to 255, for colour channels
function randomInteger(max = 256){
  return Math.floor(Math.random()*max);
}
//draw n squares at random places and sizes
function makeRandomSquares(n){
  for(let i = 0; i < n; i++){
    const size = Math.random()*(maxWH*0.15);
    //minus half the size from x,y
    //so they can overlap left and top of screen, not just bottom and right.
    const x = Math.random()*width-size/2;
    const y = Math.random()*height-size/2;
    //random rgba colour
    ctx.fillStyle = `rgba(${randomInteger()},${randomInteger()},${randomInteger()},${Math.random()*0.4})`;
    ctx.fillRect(x,y,size,size);
  }
}
//initialize with 2 squares
makeRandomSquares(2);
//make 2 more squares each click
document.addEventListener("click", function(){
  makeRandomSquares(2);
}, false);
html, body {
  margin: 0;
  padding: 0;
}
canvas {
  width: 100%;
  height: 100%;
}
<canvas id="canv"></canvas>

2 of 3
2

this is what you want?

function drawSquare(canvas, context, color){
    var x= Math.floor(Math.random()*canvas.width);
    var y= Math.floor(Math.random()*canvas.height);    
    context.fillStyle = color;
    context.fillRect (x,y, canvas.width, canvas.height)
 }
 
 let canvas=document.getElementById('canvas');
 drawSquare(canvas,canvas.getContext('2d'),'pink');
<canvas width=300 height=300 id="canvas" ></canvas>

🌐
JSFiddle
jsfiddle.net › megantaylor › cuTFa
Random Square Generator - JSFiddle - Code Playground
You get to try and use features (like the Palette Color Generator) months before everyone else. Sort and categorize your Fiddles into multiple collections. You can make as many Private Fiddles, and Private Collections as you wish! Debug your Fiddle with a minimal built-in JavaScript console.
Discussions

javascript - Generate 3000 squares procedurally - Stack Overflow
I need to build a widget that contains 3000 squares. Doing this manually would take a very long time, maybe some of you know the easiest way to generate the class .square 3000 times? I need also be... More on stackoverflow.com
🌐 stackoverflow.com
November 21, 2016
[OC] Grid Pattern Generator I made in javascript [OC] You click individual squares and set "step" amounts of square propagations. There are basic shape patterns defined: cross, square, triangle, rotate, spiral, full square.
I made this on my website migomick.com - ui is shit but the functionality is extremely strong. You can basically create patterns of shapes and rerun them to create new patterns. It's quite fascinating the macroshapes created by basic cross, square patterns pick shape click sequences of squares save click pattern rerun pattern with different steps and shapes to generate recursive patterns repeat with different sequence of clicks change theme More on reddit.com
🌐 r/dataisbeautiful
3
21
January 15, 2023
html - Adding a square in javascript - Stack Overflow
I want to create a square in JavaScript. I have made a class in CSS with square. I want to create something like a so that the square is displayed when I click... More on stackoverflow.com
🌐 stackoverflow.com
Generate a random color of a random square in Javascript - Stack Overflow
The button is supposed to change the color of a random square to random color. This is my code, I figured out how to change the random color of every square at the same time, but it should pick on... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Krazytech
krazytech.com › home › javascript to generate squares of 1 to n numbers
Javascript to generate squares of 1 to n numbers - Krazytech
March 10, 2020 - //Square.html <!DOCTYPE HTML> <?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Square.html </title> <script type="text/javascript"> function square() { var n=prompt ("Enter the limit 'n' to generate ...
Top answer
1 of 4
2

You just need a loop and create a new square on each iteration. In order to be able to access each square individually, each generated square gets its own unique id:

var cont = document.getElementById("container");

for(var i = 1; i <3001; ++i){
 var div = document.createElement("div");
 div.setAttribute("class", "square");
 div.setAttribute("id", "div" + i);
 
 var h1 = document.createElement("h1");
   h1.textContent = i;
   div.appendChild(h1);
   cont.appendChild(div);
 }
.square{
  background:#fa5339;
  color:#fff;
  width:100px;
  height:100px;
  float:left;
  border:1px solid #d63d26;
}
h1{
    height: 50%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}
<div id=container>
  
</div>

2 of 4
1

Your question is very vague.

What technologies are you willing ( or able in the case of homework like project) to use to achieve your goal?

If you have no idea how to do it then i would suggest you start learning of some jQuery, that is a javascript framework, that allows you to do some pretty cooll and easy stuff.

If you do end up using jquery, all you would have to do is to create an element lets say:

<div id="container"></div>

and then somewhere in your javascsript you would have a javascript array with the objects that you are rendering for, say an object named square { color,title,text,name,this,that }

And after that you could just create a loop,construct your html elements as string and use jquery to append the elements in your DOM. An example would be :

var myContainer = $('#container'); <--- this holds a reference to the container element using jquery
for(var i=0,len=myArray.length;i<length;i++){ <-- in my array you would have your "square" objects so that you can modify each square based on parameters like name,title,color etc
    var elementInString = '<div class="square" style="color:"'+myArra[i].color+'>';   <-- and create your parameterised square here
    $(myContainer).append(elementInString);
}

This is one way to do it. Other way include using other frameworks (Knockout,Angular etc)

I hope this helps

🌐
YouTube
youtube.com › krazytech
Javascript to generate squares of 1 to n numbers - YouTube
This video contains the Javascript to generate squares of 1 to n numbers. This script accepts a number as the input and generates the squares of all 'n' numb...
Published   May 18, 2023
Views   3K
🌐
Blogger
shuttereditz.blogspot.com › 2014 › 03 › javascript-code-magic-square-generator.html
Javascript Code- Magic Square Generator ~ Shutter
March 2, 2014 - for(t=0;;t++) { var n=prompt("Enter the dimension"); if(n%2!=0&&n>2) break; else alert("MAgic Square cannot be made"); } var last=n*n; var a=[]; for(m=0;m<n;m++) a[m]=[]; var i=0; var j=Math.floor(n/2);; for(var c=1;c<=last;c++) { if(i<0) i=n-(-i); if(i>=n) i=i-n; if(j<0) j=n-(-j); if(j>=n) j=j-n; a[i][j]=c; if(c%n==0) { i++; } else { i--; j++; } } document.write("<table border='2'>"); for(k=0;k<n;k++) { document.write("<tr>"); for(l=0;l<n;l++) { document.write("<td class='box' width='60' height='60'>"+a[k][l]+"</td>"); } document.write("</tr>"); } document.write("</table>");
🌐
Text Utility Tools
textutilitytools.com › home › text tools › text square generator tool
Text Square Generator Tool (Free & No Login)
May 19, 2025 - const cleanedText = String(originalText).replace(/(\r\n|\n|\r)/g, ' '); if (cleanedText.length === 0) { return '<pre></pre>'; // Return an empty preformatted block for empty input } const length = cleanedText.length; const side = Math.ceil(Math.sqrt(length)); // Calculate the side length of the square // Sanitize paddingCharacter: // Use the first character of the provided string.
Find elsewhere
🌐
Damienmasson
damienmasson.com › tools › latin_square
Balanced Latin Square Online Generator
The code of this generator is open source. Feel free to copy the following function to generate balanced latin squares directly from your code. Javascript
Top answer
1 of 5
3

in your let array = ['square1', 'square2', 'square3'];, if you pass in the variables directly rather than strings, it should work. Right now you are doing 'square1'.style.backgroundColor =

2 of 5
0

In your code, Math.floor should be within parenthesis instead of square brackets like:

let randomNumber = Math.floor(Math.random() * 3);

Then you should get the element by id from the squareRND like:

document.getElementById(squareRND).style.backgroundColor = randomColor

You should also run the colorChange();

For example:

let button = document.getElementById('button');
const changeColorOfaRandomSquareToRandom = () => {
  //This I hope will pick a random square
  let randomSquare = () => {
    let array = ['square1', 'square2', 'square3'];
    let randomNumber = Math.floor(Math.random() * 3);
    return array[randomNumber]
  };

  // I assign the value of the randomSquare function to a new variable
  let squareRND = randomSquare();
  console.log(randomSquare());
  //This picks a random number
  let rgb = (num) => {
    return Math.floor(Math.random() * num);
  };

  //This picks a random color
  let colorChange = () => {
    let randomColor = 'rgb(' + rgb(255) + ',' + rgb(255) + ',' + rgb(255) + ')';
    document.getElementById(squareRND).style.backgroundColor = randomColor;
  };
  colorChange();
};

button.onclick = changeColorOfaRandomSquareToRandom;
#square1 {
  background-color: lightpink;
  width: 200px;
  height: 200px;
  display: flex;
  margin-top: 200px;
}

#square2 {
  background-color: lightblue;
  width: 200px;
  height: 200px;
  display: flex;
  margin-top: 200px;
}

#square3 {
  background-color: lightgreen;
  width: 200px;
  height: 200px;
  display: flex;
  margin-top: 200px;
}

#squares {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

#button {
  width: 75px;
  height: 25px;
  margin-top: 20px;
  margin-left: 600px;
}
<div id="squares">
  <div id="square1">
  </div>
  <div id="square2">
  </div>
  <div id="square3">
  </div>
</div>
<button id="button">Click me</button>

🌐
Reddit
reddit.com › r/learnprogramming › [javascript] generate a 3x3 'magic square'?
r/learnprogramming on Reddit: [Javascript] Generate a 3x3 'Magic Square'?
April 8, 2013 -

Is there any easy way to go about writing code to generate the 3x3 magic square (where the sum of the numbers in each row/column/diagonal is always 15)? I'm fairly new to javascript so just some basic understanding of different ways to go about creating and automatically assigning values to an array would be much help

🌐
CodePal
codepal.ai › code generator › javascript square function
JavaScript Square Function - CodePal
April 26, 2023 - Create a simple 20-pixel square in JavaScript using the document.createElement method, ideal for learning shape creation.
Top answer
1 of 3
105

Note: Questions like this change over time as browser engines change how their optimizations work. For a recent look comparing:

Math.pow(x1, 2)
x1 * x1
x1 ** 2                  // ES6 syntax

See this revised performance test and run it in the browsers you care about: https://jsperf.com/math-pow-vs-simple-multiplication/32.

As of April 2020, Chrome, Edge and Firefox show less than 1% difference between all three of the above methods.

If the jsperf link is not working (it seems to be occasionally down), then you can try this perf.link test case.

Original Answer from 2014:

All performance questions should be answered by measurement because specifics of the browser implementation and the particular scenario you care about are often what determine the outcome (thus a theoretical discussion is not always right).

In this case, performance varies greatly by browser implementation. Here are are results from a number of different browsers in this jsperf test: http://jsperf.com/math-pow-vs-simple-multiplication/10 which compares:

Math.pow(x1, 2)
x1 * x1

Longer bars are faster (greater ops/sec). You can see that Firefox optimizes both operations to be pretty much the same. In other browsers, the multiplication is significantly faster. IE is both the slowest and shows the greatest percentage difference between the two methods. Firefox is the fastest and shows the least difference between the two.

2 of 3
34

In ES6 you can do the following with Exponentiation (x ** y), which produces the same result as Math.pow(x,y):

function squareIt(number) {
  return number ** 2;
}

console.log(squareIt(5));

or you can use a JavaScript library called BigInteger.js for the purpose.

alert(bigInt(5).square());
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>

🌐
DataFlair
data-flair.training › blogs › create-a-magic-square-in-javascript
Create a Magic Square in Javascript - DataFlair
September 28, 2025 - Here the most important tag is <input> which takes values from the user so that we can further process them in our JS file. And we have used a table tag to make a real three by three magic square.
🌐
Catonmat
catonmat.net › tools › generate-square-numbers
Generate a List of Squares
January 16, 2018 - This perfect square list generator works entirely in your browser and is written in JavaScript. It uses a simple for loop to calculate count (specified in options) square numbers. The for loop runs count times.
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript square a number
How to Square a Number in JavaScript | Delft Stack
February 2, 2024 - The Math.pow() method is a built-in JavaScript function that allows you to raise a number to a specified exponent. Its primary purpose is to calculate the power of a number. The method takes two arguments: the base number and the exponent.
🌐
CodePen
codepen.io › cameronsilber › pen › NxvVER
Bouncing Squares
First pen created implementing a for loop that will create many squares over again on the canvas. this then uses arrays an the push command to add velo...
🌐
CodePal
codepal.ai › code generator › draw a square in javascript
Draw a Square in JavaScript - CodePal
September 27, 2023 - const sideLength = 5; const squareDrawing = drawSquare(sideLength); console.log(squareDrawing); Create code in seconds with CodePal AI · Jump to generated code · Let us know if this guide helped you or if you have suggestions for improvement. Yes, it helped! 0 Needs improvement 0 · Subscribe to receive coding tips, tutorials, and updates straight to your inbox. Details · Language · JavaScript ·