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 OverflowI 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>
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>
javascript - Generate 3000 squares procedurally - Stack Overflow
[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.
html - Adding a square in javascript - Stack Overflow
Generate a random color of a random square in Javascript - Stack Overflow
Videos
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>
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
var square = document.createElement('div');
square.className = 'square';
document.body.appendChild(square);
Here's the fiddle: http://jsfiddle.net/Ysw9n/
If you use jquery it's really a simple thing to do:
$("#your-button-id").click(function() {
$("#your-square-parent-id").append('<div class="your-square-class"> </div>');
});
But you can do that without jquery as well as Joseph stated above. Anyways, hope it is useful.
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 =
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>
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
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.

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>