Course notes 17
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses

Using the Javascript Math Object Part 1

Javascript offers a robust Math object with methods and values fulfilling many common and useful calculations. Properties are accessed by directly calling the Math object followed by the desired method. When interacting artistically with the canvas, the creative implementation of math will become the heart of any successful endeavor. The only way to fully understand how various functions can be used to creatively code is to play around with them. The examples below describe the syntax of using a selection of the more useful Math properties and provide some interesting canvas implementations.


Rounding

Javascript provides two functions to facilitate rounding numbers. Both are very simple, requiring only one value to be passed: the number to be rounded.

  • Math.ceil() - will return the passed number rounded up to the next integer. If an integer is passed, the same value will be returned.

  • Math.floor() - will return the passed number rounded down to the previous integer. If an integer is passed, the same value will be returned.


Random

Javascript's Math.random() is the function used to generate a random number. The function itself returns a value in the range of 0 to .99999(...).

To generate a value between 0 and some other number, use the formula:
Math.floor(Math.random()*(high bound+1))

To generate between an arbitrary range, we use the formula:
Math.floor(Math.random()*(high bound - low bound+1)) + low bound

Starting with a simple example, we can randomize the color of a rectangle drawn onto the canvas. When declaring the fillStyle, instead of using static values, a random number between 0 and 255 is generated for each of the RGB properties.

    <script>
        function init(){
            var canvas = document.getElementById('ex01');
            var ctx = canvas.getContext('2d');
           
             ctx.fillStyle = 'rgb('+Math.floor(Math.random()*(255+1))+',
                     '+Math.floor(Math.random()*(255+1))+', '+Math.floor(Math.random()*(255+1))+')';
             ctx.fillRect(canvas.width/2-25,canvas.height/2-25,50,50);
        }
    </script>
    
    <body onload='init()'>
    <canvas id="ex01" width='400px' height='300px'></canvas>
    
    

Taking it a step further, random numbers can generate random numbers. In the next example a random number determines the Y location of 3x3 rectangles as they are drawn across the screen. However, instead of maintaining a steady range of random values as the rectangles are drawn, each iteration augments the high and low values by another random number.

    <script>
        function init(){
            var canvas = document.getElementById('ex02');
            var ctx = canvas.getContext('2d');
            var width = canvas.width;
            var height = canvas.height;
            
            var points = 500;
	         var rand = 0;
            for(var i = 1; i <= points; i++){
                ctx.fillRect((width/points)*i,(height/2)+Math.floor(Math.random()*(rand+rand+1)-rand),3,3);
                rand+=Math.floor(Math.random()*(10+1)-5);
            }
    </script>
    
    <body onload='init()'>
    <canvas id="ex02" width='400px' height='300px'></canvas>
    
    

Here is an example of a function you can call and feed it two numbers - the highest number and the lowest number you want - and the function will choose a random number for you:

<script>
  function chooseNum(theMin, theMax) {
     var theRange = (theMax - theMin) + 1;
     var randomNum = Math.floor((Math.random() * theRange) + theMin); 
     return randomNum;
  }

  function drawbox() {
      var canvas = document.getElementById('drawrand');
      var ctx = canvas.getContext('2d');
      ctx.fillRect(chooseNum(100,350),chooseNum(50,250),50,50);
  } 
     
</script>