westan25
westan25

Reputation: 11

I'm trying to create a Mondrian with HTML and JavaScript

I've got an assignment for Uni on creating Mondrian with the aim of the project to Write code to generate 100 randomly sized rectangles at random locations within a canvas.

I've attempted it and it looks like this (HTML)

<!doctype html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<title>Mondrian</title>
<script src="Mondrian.js"></script>
<link rel="stylesheet" href="Canvas style.css">
</head>
<body>
<canvas id="myCanvas" width=400 height=400>
Your browser does not support the HTML5 canvas tag</canvas>
</body>
</html>

Javascript

window.addEventListener( 'load', drawMondrian);
function drawMondrian ()
{
var canvas = document.getElementById ('myCanvas' );
var context = canvas.getContext ('2d' );
var randomSize = Math.random() * 200;
var randomXposition = Math.random() * 500;
var randomYposition = Math.random() * 500;
var shape = 1;

for (var i = shape; i < 100; i +=1)
{
context.fillRect (randomXposition, randomYposition, randomSize, randomSize);
}
}

I need assistance on how to get the rectangles to form all at once because so far the rectangles only appear one at a time, everytime I run or refresh the page.

Upvotes: 1

Views: 405

Answers (1)

synthet1c
synthet1c

Reputation: 6282

You need to move your position and size declaration inside the loop. In your code you are declaring the size and position only once, then redrawing that 100 times.

    window.addEventListener( 'load', drawMondrian);
    function drawMondrian ()
    {
      var canvas = document.getElementById ('myCanvas' );
      var context = canvas.getContext ('2d' );
      var shape = 1;
      var randomSize, randomXPosition, randomYposition;
    
      for (;shape < 100; shape += 1)
      {
        randomSize = Math.random() * 200;
        randomXposition = Math.random() * 500;
        randomYposition = Math.random() * 500;
        context.fillRect (randomXposition, randomYposition, randomSize, randomSize);
      }
    }
<canvas id="myCanvas" width=400 height=400>
Your browser does not support the HTML5 canvas tag</canvas>

Upvotes: 2

Related Questions