user2619395 user2619395 - 1 year ago 82
HTML Question

Random Positioned Boxes

I'm having a little trouble with randomly positioning a bunch of random boxes throughout a page.

The goal is to have a randomly amount of boxes show up in random positions and the boxes are to be random colors on a page. The boxes should also be overlapping, making them truly in random positions.

Thus far all I have is one randomly colored box on the page, clearly not randomly positioned. I'm suck of where to go from here with the positioning and creating a bunch of random boxes...

Please note JQuery cannot be used.


<!DOCTYPE html>
<meta charset="UTF-8">
<title>Ramdom Boxes</title>
<script src="A2Q1.js"></script>



window.onload = init;

function init() {
//when page is loaded create a bunch of boxes randomly throughout the page
//get the body element of the document
var body = document.getElementsByTagName("body")[0];

//create the canvas tag
var canvas = document.createElement("canvas");
canvas.height = 100;
canvas.width = 100;
var context = canvas.getContext("2d");

//create the box and append onto the canvas
var colour = '#'+ Math.round(0xffffff * Math.random()).toString(16);
context.fillStyle = colour;

//append the canvas onto the body

Answer Source

It would be better to resize the canvas as much as window size. In order to draw a bunch of rectangles, use for loop to execute draw rectangle code repeatedly. Set each rectangle's position in window width and height (Math.random() * window.innerWidth, Math.random() * window.innerHeight).

Here is my sample code.

function init() {
    var body = document.getElementsByTagName("body")[0];
    var canvas = document.createElement("canvas");
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
    var context = canvas.getContext("2d");

    //  Opacity makes a good appearance when objects are overlapped 

    //  Repeat to draw a rectangle 100 times
    for(var i=0;i<100;i++){
        var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
        context.fillStyle = color;

        //Each rectangle is at (0 ~ width of window, 0 ~ height of window)
        //Each rectangle's size is (20 ~ 100, 20 ~ 100)     
        context.fillRect(Math.random()*window.innerWidth, Math.random()*window.innerHeight, Math.random()*80+20, Math.random()*80+20);

window.onload = init;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download