Exercise 7 · Chapter: Pixel ProjectsOptional+50 XP
Gradient Rectangle
Read a number N and a hex color (like #ff0000) from input.
Create an N x N grid with a "white" border (1 pixel thick). Fill the inside with a gradient that goes from "#000000" (black) on the left to the given color on the right.
To compute each gradient color, use the formula for each channel (red, green, blue):
value = Math.floor(targetValue * t) where t goes from 0.0 (left) to 1.0 (right).
Use parseInt(hexString, 16) to convert hex to a number, and value.toString(16).padStart(2, "0") to format it back.
Example for N=8 with color #ff0000:
Don't change the console.log statements at the bottom.
Expected output
8 white #000000 #ff0000
Need a hint?
3 available · costs 5 XP each
javascript
let n = Number(prompt());
let color = prompt();
// Parse the hex color into r, g, b components
// let r2 = parseInt(color.slice(1, 3), 16); etc.
let grid = [];
// Create N x N grid
// Border (row 0, row n-1, col 0, col n-1): "white"
// Inside: gradient from "#000000" to the given color
// t = (col - 1) / (n - 3) for inner columns
let __grid__ = grid;
// Don't change below this line
console.log(grid.length);
console.log(grid[0][0]);
console.log(grid[1][1]);
console.log(grid[1][n - 2]);
Output
Run your code to see the output here.