Affichage des articles dont le libellé est JavaScript Triangle. Afficher tous les articles
Affichage des articles dont le libellé est JavaScript Triangle. Afficher tous les articles

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








JavaScript Random Triangle Generator

How To Create a Random Triangle Generator Using Javascript  


JavaScript Random Triangle Generator


In this Javascript tutorial, we will create a JavaScript code that generates a canvas filled with random triangles. Using the HTML5 canvas element and its context, we will create an interactive display of colorful shapes. Let's dive into the code and understand how it works.



Project Source Code:


<!DOCTYPE html>
<html>
<head>
<title>Random Triangle Generator</title>

<style>
body{ background-color: #ddd; }

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

#generate-btn{ background-color: #4caf50; color: #fff;
padding: 10px 20px; border:none;
border-radius: 4px; cursor: pointer; margin-top: 10px;
}

</style>

</head>
<body>

<canvas id="canvas"></canvas><br>
<button id="generate-btn">Generate Random Triangle</button>

<script>

// Get the canvas element and its context
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Get the generate button and attach a click event listener to it
const generateBtn = document.getElementById("generate-btn");
generateBtn.addEventListener("click", generateTriangles);

// This function generates triangles on the canvas
function generateTriangles(){

// Clear the canvas before drawing new triangles
ctx.clearRect(0,0, canvas.width, canvas.height);

// Generate 100 random triangles
for(let i = 0; i < 100; i++){
// Generate random x and y coordinates
// for each point of the triangle
let x1 = Math.floor(Math.random() * canvas.width);
let y1 = Math.floor(Math.random() * canvas.height);

let x2 = Math.floor(Math.random() * canvas.width);
let y2 = Math.floor(Math.random() * canvas.height);

let x3 = Math.floor(Math.random() * canvas.width);
let y3 = Math.floor(Math.random() * canvas.height);

// Get a random color for the triangle
let color = getRandomColor();

// Draw the triangle on the canvas
// using the generated coordinates and color
drawTriangle(x1, y1, x2, y2, x3, y3, color);

}
}

// This function draws a triangle on the canvas
// using three sets of coordinates and a color
function drawTriangle(x1, y1, x2, y2, x3, y3, color){

ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();

}

// This function generates a random color in hexadecimal format
function getRandomColor()
{
let letters = "0123456789ABCDEF";
let color = "#";

// Generate six random hexadecimal digits to form a color
for(let i = 0; i < 6; i++)
{
color += letters[Math.floor(Math.random() * 16)];
}

return color;
}


</script>

</body>
</html>



Code Explanation:

this JavaScript code, create an engaging display of 100 random triangles on an HTML5 canvas. 
The dynamic nature of the code allows for endless possibilities, as each execution will produce a different arrangement of colorful shapes. 
Experimenting with variations of this code can lead to even more captivating visual effects.

This JavaScript code performs the following actions:

1 - Obtaining the Canvas and Context: The first step is to retrieve the canvas element and its 2D rendering context. These elements are accessed using the getElementById method and stored in the canvas and ctx variables, respectively.

2 - Event Listener: The code attaches a click event listener to the "Generate" button (generateBtn). When the button is clicked, the generateTriangles function is called.

3 - Generating Triangles: The generateTriangles function is responsible for drawing 100 random triangles on the canvas. It starts by clearing the canvas using the clearRect method.

4 - Triangle Generation: Inside the generateTriangles function, a loop generates the necessary coordinates and color for each triangle. For each iteration, random x and y coordinates are generated for the three points of the triangle (x1, y1, x2, y2, x3, y3). These coordinates are generated using the Math.random() function and adjusted to fit within the canvas dimensions.

5 - Color Generation: The getRandomColor function generates a random hexadecimal color code by iterating six times and appending a random digit from the set of letters "0123456789ABCDEF" to the color string.

6 - Drawing the Triangle: The drawTriangle function takes the generated coordinates and color as parameters. It uses the beginPath, moveTo, lineTo, and closePath methods to define the triangle's shape. The fillStyle property is set to the generated color, and the triangle is filled using the fill method.


OUTPUT:


Draw Random Triangles In Javascript