0

So I have a banner on a site, but I want to make it so that each time the page loads, a different image appears. More precisely, I want (say 50) squares (say having a black border, white fill) of random size (say from 5 pixels to 20 pixels in size) in random positions of a 750x63 px frame, with a white background.

What would be the best way to do this? I know a little JavaScript and HTML (and am very willing to learn more), but I really have no idea where to start. This is for my personal webpage, which I wish to spruce up a bit. Right now the fanciest code I have is some JavaScript for a simple Lightbox interface.

Jānis Lazovskis
  • 190
  • 2
  • 13

1 Answers1

0

Wow, that was easier and more fun than I expected. Here's the code, that goes in the <body> section of my HTML code, optimized for a 750x80px frame. The random integer generator I got from this other question.

<canvas id="canvas" width="750" height="80"></canvas>
<script type="text/javascript">
  //Random integer generator
  function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');
    //Loop to make 80 squares
    for (var i=0;i<80;i++) {
      //The x-position of the square, with 5px padding in frame
      var sx = getRandomInt(5,705);
      //The y-position of the square, with 5px padding in frame
      var sy = getRandomInt(5,35);
      //The height of the square, smallest 8x8px, largest 40x40px
      var sh = getRandomInt(8,40);
      //First, create a black square
      ctx.fillStyle = "rgb(0,0,0)";
      ctx.fillRect (sx, sy, sh, sh);
      //Second, create a white square that's 4px shorter and thinner,
      //leaving a boundary of 2px
      ctx.fillStyle = "rgb(255,255,255)";
      ctx.fillRect (sx+2, sy+2, sh-4, sh-4);
    }
  } 

  draw();
</script>

The approach I used is from a Mozilla Developers page. The result is something like this:

the result

Hooray!

Community
  • 1
  • 1
Jānis Lazovskis
  • 190
  • 2
  • 13