October 27, 2007 0

HTML Canvas – Random Lines

By Levi Senft in Web

This is very much the kind of demo you would expect to find in 90s game programming books. The random line generator. It draws randomly colored lines in with random coordinates. Here is the code:

    1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    2 <html>
    3     <head>
    4         <title>Random Lines</title>
    5         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    6         <style type="text/css">
    7             #Canvas {
    8                 width: 640px;
    9                 height: 480px;
   10             }
   11
   12         </style>
   13     </head>
   14     <body>
   15         <canvas id="Canvas" width="640" height="480"></canvas>
   16
   17         <script type="text/javascript">
   18
   19             // Get a reference to our canvas element
   20             var canvas = document.getElementById("Canvas");
   21
   22             // Get a reference to the canvas's drawing context
   23             var context = canvas.getContext("2d");
   24
   25             // These variables will contain the coordinates used to plot our lines
   26             var x1, y1, x2, y2;
   27
   28             // These variables will store our color values
   29             var red, green, blue;
   30
   31             // execute this loop 100 times (0-99 = 100)
   32             for (var loop = 0; loop < 99; loop++) {
   33                 // pick random color values
   34                 red = Math.floor(Math.random()*255);
   35                 green = Math.floor(Math.random()*255);
   36                 blue = Math.floor(Math.random()*255);
   37
   38                 // build a string representing our color that strokeStyle can deal with
   39                 var hex = "rgb(" + red + "," + green +"," + blue + ")";
   40
   41                 // assign the color to strokeStyle
   42                 context.strokeStyle = hex;
   43
   44                 // pick random coordinates for the lines
   45                 x1 = Math.floor(Math.random()*640);
   46                 y1 = Math.floor(Math.random()*480);
   47                 x2 = Math.floor(Math.random()*640);
   48                 y2 = Math.floor(Math.random()*480);
   49
   50                 // draw the line at the random coordinates
   51                 context.beginPath();
   52                 context.moveTo(x1, y1);
   53                 context.lineTo(x2, y2);
   54                 context.closePath();
   55
   56                 context.stroke();
   57             }
   58
   59         </script>
   60     </body>
   61 </html>
   62 

You can check out the demo here. I’ve tested this in Safari, Firefox and the latest WebKit.

Leave a Reply