JavaScript - Generating Random Shapes with JavaScript

How To Create a Random Shapes Generator Using Javascript  


JavaScript - Generating Random Shapes with JavaScript


In this Javascript tutorial, we will create a JavaScript code that generates and draws random shapes on an HTML canvas.
we will use the HTML canvas element and various JavaScript functions to generate and draw random shapes on the canvas.



Project Source Code:



<!DOCTYPE html>
<html>

<head>
<title>Random Shapes</title>

<style>

body{ background-color: #ddd }

#canvas{ border: 1px solid #555; background-color: #fff; }

</style>

</head>

<body>

<canvas id="canvas" width="500" height="500"></canvas>

<script>
const canvas = document.getElementById("canvas");

// This function generates random x and y coordinates within a 500x500 square.
function getRandomCoordinates(){

let x = Math.random() * 500;
let y = Math.random() * 500;
return [x,y];
}
// This function draws a random shape on the canvas,
// based on the input parameter "shape".
function drawRandomShape(context, shape){

// if you want to clear the canvas before drawing a new shape
// context.clearRect(0,0,canvas.width, canvas.height);

// Start a new path on the canvas.
context.beginPath();
// Depending on the value of the "shape" parameter, draw a circle,
// square, or triangle.
switch(shape){
case "circle":
let coordinatesC = getRandomCoordinates();
// Draw a circle with a radius of 50
// and center coordinates generated by getRandomCoordinates().
context.arc(coordinatesC[0], coordinatesC[1], 50, 0, 2 * Math.PI);
break;
case "square":
let coordinatesS = getRandomCoordinates();
// Draw a square with a side length of 50
// and coordinates generated by getRandomCoordinates().
context.rect(coordinatesS[0], coordinatesS[1], 50, 50);
break;
case "triangle":
let cord1 = getRandomCoordinates();
let cord2 = getRandomCoordinates();
let cord3 = getRandomCoordinates();

// Draw a triangle with vertices at the randomly generated coordinates.
context.moveTo(cord1[0], cord1[1]);
context.lineTo(cord2[0], cord2[1]);
context.lineTo(cord3[0], cord3[1]);

context.closePath();

break;
}

// Set a random color for the shape.
let color = getRandomColor();
context.fillStyle = color;
context.fill();

}


// This function generates a random hexadecimal color code.
function getRandomColor()
{
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++)
{
color += letters[Math.floor(Math.random() * 16)];
}

return color;
}

// This function captures user input,
// and if the key pressed matches a predefined shape key,
// it calls the drawRandomShape() function with the appropriate shape parameter.
window.onkeypress = function(e){

let context = canvas.getContext('2d');

if(e.key === 'c')
{
drawRandomShape(context, "circle");
}
else if(e.key === 's')
{
drawRandomShape(context, "square");
}
else if(e.key === 't')
{
drawRandomShape(context, "triangle");
}

}

</script>

</body>

</html>


Code Explanation:

This JavaScript code performs the following actions:

1 - Setting up the Canvas: The code begins by declaring an HTML canvas element with the id "canvas" and specifying its width and height. This canvas element serves as the drawing area for the shapes.

2 - Generating Random Coordinates: The getRandomCoordinates() function generates random x and y coordinates within a 500x500 square. It uses the Math.random() method to generate random values and returns an array with the x and y coordinates.

3 - Drawing Random Shapes: The drawRandomShape() function takes two parameters: the canvas context and the shape to be drawn. Inside this function, a switch statement is used to determine which shape to draw based on the input parameter "shape".
Circle: If the shape is "circle", the function generates random coordinates using getRandomCoordinates() and draws a circle on the canvas using the arc() method.
Square: If the shape is "square", the function generates random coordinates and draws a square on the canvas using the rect() method.
Triangle: If the shape is "triangle", the function generates three sets of random coordinates and draws a triangle on the canvas using the moveTo() and lineTo() methods.

4 - Setting Random Colors: The getRandomColor() function generates a random hexadecimal color code by concatenating random letters and numbers from the string "0123456789ABCDEF". The generated color is then applied to the shape using the fillStyle property of the canvas context.

5 - Capturing User Input: The window.onkeypress event captures user input when a key is pressed. The function checks the pressed key against predefined shape keys ('c' for circle, 's' for square, 't' for triangle) and calls the drawRandomShape() function accordingly, passing the appropriate shape and the canvas context.



OUTPUT:


Generating Random Shapes Using JavaScript








Share this

Related Posts

Previous
Next Post »