Sure! Here's an example of a JavaScript program that draws a random color square centered on a canvas:
```javascript
// Canvas setup
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Constants
const SIDE_LENGTH = 200;
// Generate a random color
function getRandomColor() {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// Draw a random color square
function drawRandomSquare() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Get a random position for the square
const x = canvas.width / 2 - SIDE_LENGTH / 2;
const y = canvas.height / 2 - SIDE_LENGTH / 2;
// Get a random color
const color = getRandomColor();
// Draw the square
ctx.fillStyle = color;
ctx.fillRect(x, y, SIDE_LENGTH, SIDE_LENGTH);
}
// Call the drawRandomSquare function to draw the initial square
drawRandomSquare();
```
In this example, we first set up the canvas using the `canvas` element and `getContext` method. We define the `SIDE_LENGTH` constant to determine the size of the square.
The `getRandomColor` function generates a random color using hexadecimal values. It loops six times to generate a random string of characters that represents a color code.
The `drawRandomSquare` function is responsible for drawing the square. It starts by clearing the canvas using the `clearRect` method. Then it calculates the position for the square, centered on the canvas. Next, it retrieves a random color using `getRandomColor`. Finally, it uses the `fillStyle` property to set the color and `fillRect` method to draw the square on the canvas.
To initially draw the square, we call the `drawRandomSquare` function.
Write a program that draws a random color square centered on the graphics canvas. The sides of the square should be SIDE_LENGTH. use java script
1 answer