Tuesday 17 January 2017

Javascript & HTML canvas - randomly generated grey scale value

Link to finished example:
http://www.w3schools.com/code/tryit.asp?filename=FBSXKSA3CNK6

I have been playing with and learning more about Javascript and the <canvas> feature for a bit and to be honest there have been some bits that are confusing. But I have finally managed to create a randomly generated 2d cube-map (I also added in a update function which makes it recreate the random map every 200 milliseconds).



Set up the <canvas>

Firstly I created the HTML canvas, which is 500 x 500px, has an ID of 'myCanvas' and set the border to red in the styling:

<canvas id="myCanvas" width="500" height="500" style="border:4px solid red;">


Javascript creating the canvas

Next it's jumping into Javascript and I grab the canvas element from the HTML, and set it's type to 2D storing them in the canvas and context variable.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');


More variables..

Also in the initial stages I've set up variables to create how many squares wide and high, and created an empty array that will store the colours later.

 var cols = 17;
 var rows = 17;
 var colors = [];

Next , I set up the function which executes 'functionGo' every 200 milliseconds using the Javascript window.setInterval to do so.

window.setInterval(functionGo, 200);

Next up, I create a function which is used later to create a random number between min and max value. 

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


Finally I will create the function functionGo that creates the cubes. So to break it down:

- First for loops, which cycles through the array (colors), and creates a new array per spot - the length of that loop is determined by the cols variable which currently is 17. So it creates 17 new array's. (basic multi-dimensional array).
- Second for loop, which cycles through each new array created and sets variable x and y, to the current position * 30 (each square is 30x30). Then for each spot, a square is created with the beginPath() function, rect() function, fillStyle() function (the colour is generated using the random number generator we created earlier. Between the values 20-100.), and finally the fill() function.

function functionGo() {
for(var i=0; i<cols; i++) {
           colors[i] = [];
     for(var j=0; j<=rows; j++) {
             var x = i * 30;
             var y = j * 30;
                            
        context.beginPath();
context.rect(x, y, 30, 30);
context.fillStyle = ('hsl(0,0%,' + getRandomInt(20,100) + '%)' );
context.fill();
     
         }
     }
}

And that concludes this little script that randomly generates a 17 x 17 square map in the canvas HTML element.

No comments:

Post a Comment