JavaScript Coding Tutorial — Part 2

xpoly
xpoly
Published in
6 min readMar 7, 2022

--

Continuing right from where we left off from Part 1, to add even more awesome randomness and a little housekeeping.

Before we jump into how to randomize more things than just the x horizontal and y vertical coordinates and rectangle height and widths, let’s look at a couple best practices.

One thing that’s considered a good practice is to add in a line of text in between the canvas tags, just in case the user’s web browser doesn’t support the canvas element.

<canvas id=”myCanvas” width=”800" height=”600">
Your browser does not support the HTML5 canvas tag.
</canvas>

In reality, depending on your target user audience, there’s an estimated less than 3% of web browsers that wouldn’t show your canvas element and that number is getting smaller and smaller every year. If you are ever not sure about using certain tags or elements on your web page or web app, you can use websites like caniuse.com. If we want to check on the canvas tag specifically, then we can go to the following link: https://caniuse.com/canvas

Another best practice nowadays when you are moving around things or animating them, like we moving around our paint brush and drawing rectangles, is to request an animation rate. So, instead of having that drawLoop() function with a setInterval() timer running every 50 milliseconds, we will instead “ask” the user’s web browser what is the most appropriate animation frame rate to run our animation.

Since we want to disable the drawLoop() function, we can comment it out to tell the browser that these are just our comments or notes and not actual JavaScript code to execute. We do this by adding adding forward slashes (usually on your keyboard above the question mark key) and asterisks/star symbols (usually above the number 8 on your keyboard). On most keyboards, you can press the SHIFT key and the question mark key to enter the forward slash and the SHIFT key and the number 8 key to enter the asterisk symbol.

/*function drawLoop() {
window.setInterval(() => {
drawRect()
}, 50);
}
drawLoop();*/

The next things that’s a good practice is to use and initialize function or “init” for short. It’s just as it sounds, it’s what the browser will do initially or first. So, we can create an init() function that will run before any other functions and then add a single line comment/note with the double forward slashes.

function init() {
// 2D Canvas requests frame rate (~60fps).
window.requestAnimationFrame(drawRect);
}

As you can see we have made a code comment explaining that we are using a two dimensional canvas and that the web browser will usually request a frame rate of 60 frames per second (fps). That helps remind us that if we are moving something, it will most likely animate around that speed. Now to run that init() function, we need to call it, by adding it right above the ending </script> tag, like the following.

init();
</script>

Now, if you run your JavaScript web application, you will notice it only paints one square and then stops. This is because we need to not just run it initially, but we need to keep animating it, thus, every time it draws a rectangle, we want it to draw another one, so we add this new line at the bottom of the drawRect() function.

function drawRect() {

window.requestAnimationFrame(drawRect);
}

Ok, now if you refresh your browser and run it, you might even notice the animation or drawing of the rectangles is every so slightly “smoother”.

Alright, now onto something a bit more fun… More randomness.

Let’s do some random colors, that sounds pretty fun. Let’s start by making a new function appropriately named randomColor, then let’s make a comment with the double forward slashes, like before to add a note to ourselves that this particular computer color value is in what’s called a hexadecimal color value format. So, just like a hexagon has 6 sides, which you surely learned about in school, the hexadecimal color value is 6 characters in length.

function randomColor() {
// Generate random hexadecimal color.
var randomNum = Math.floor(Math.random()*16777215).toString(16);
return “#” + randomNum;
}

Don’t worry about understanding every single part of this, yet, we’ll get there soon enough. Right now, it should suffice to understand that this new function is going to pick a random color out of about 16.7 million possible colors and “return” or output back to us a hexadecimal color value, that will look something like: #0099cc or #669977 or #333333 and so on.

To use our new randomColor() function, we only need to replace our stroke style color line: ctx.strokeStyle = “#fc636c”;

Now if you run your JavaScript code again with this new line, you should see the random colors for the borders of our rectangles.

ctx.strokeStyle = randomColor();

Using our randomColor function to display a random color border for each rectangle.
Using our randomColor function to display a random color border for each rectangle.

Cool, random colors can be quite fun and have limitless possibilities when combined with other interesting things. What else can we make random?

How about let’s make the border line or stroke width random, but in this case we want a very limited range that the random number will be generated from. Let’s go ahead and add this new function below our randomColor() function.

function getRandomNum(min, max) {
// Random whole number between min (inclusive) and max (exclusive).
return Math.floor(Math.random() * (max - min)) + min;
}

In this case, we have a getRandomNum() function that has a min and max inside its parentheses, which means we will tell it the minimum and maximum range of numbers we want the random number to be inside.

So, in this case we will run or call the function with a minimum of 1 and a maximum of 5, but we have a comment that reminds us that this the minimum is inclusive and the maximum is exclusive. That means that the following JavaScript code will return us a whole number (integer) of 1, 2, 3 or 4… but, not 5.

getRandomNum(1, 5)

So, if we change the line of code that sets the lineWidth to 3 to the following line, we should see that the rectangles have random line widths in that range for their borders now.

ctx.lineWidth = getRandomNum(1, 5);

Try different random rectangle border line stroke widths and see what you can create.
Try different random rectangle border line stroke widths and see what you can create.

Be sure to take a minute and play with the numbers some and see what effects you can create in your simple motion art-like piece.

But, what about the inside rectangle fill with the RGBA color that creates the alpha transparency or semi-transparent blueish fill?

Sure, no problem, we can use much of what we’ve learned to create a new function for RGBA (red, green, blue and alpha transparency).

function getRandomRGBA(min, max) {
// Random RGB numbers between min (inclusive) and max (exclusive).
var red = Math.floor(Math.random() * (max - min)) + min;
var green = Math.floor(Math.random() * (max - min)) + min;
var blue = Math.floor(Math.random() * (max - min)) + min;
return “rgba(“ + red + “,” + green + “,” + blue + “, 0.25)”;
}

So close to our getRandomNum() function, but with a few changes, to provide a random number for each color channel and then return a formatted string of text back.

Now we use or call the function with a min and max, just like before to set the fill style of the rectangle. The way that RGB color values work on computers we set a max of up to 255, which isn’t perfect code, but it is close enough for right now. Better to iterate your code, keep the momentum and then later you can always go back to improve your code, by optimizing and fixing problems in your code often referred to as “software bugs”.

ctx.fillStyle = getRandomRGBA(0, 255);
ctx.fillRect(randomX, randomY, randomWidth, randomHeight);

Using our new getRandomRGBA function adds a nice additional level of color depth?
Using our new getRandomRGBA function adds a nice additional level of color depth?

One thing to note, is that since we are getting a random number with a maximum exclusion, it wouldn’t actually ever give us the value of 255, so to get a more accurate 0 to 255 range of random values, we could put in 256.

ctx.fillStyle = getRandomRGBA(0, 256);

And… that’s the end of the JavaScript Coding Tutorial — Part 2

--

--

xpoly
xpoly
Editor for

XPOLY is about learning many computer languages and skills, through the use of polygons, gaming and fun. “x” for a specific target and “poly” for meaning many.