Exerpad
Lesson · Chapter: Pixel Projects+10 XP for reading

Intro to Pixels

You can create colorful pixel art with JavaScript! Just create a special variable called __grid__ holding an array of arrays of color names, and you'll see your creation appear as colored pixels.

Your First Grid

Try running this code:

javascript
let __grid__ = [
["red", "blue"],
["green", "yellow"]
];
Output
Press Run to see the output.

You should see a 2x2 colored grid appear!

How It Works

__grid__ is an array of rows. Each row is an array of color names. You can use any CSS color name like "red", "blue", "green", "orange", "purple", "black", "white", "pink", "gold", and many more.

You can also use hex colors like "#ff0000" for red or "#00ff00" for green.

Building a Grid with Loops

Instead of typing every color by hand, use loops to build patterns:

javascript
let grid = [];
for (let row = 0; row < 5; row++) {
let line = [];
for (let col = 0; col < 5; col++) {
if ((row + col) % 2 === 0) {
line.push("dodgerblue");
} else {
line.push("white");
}
}
grid.push(line);
}

let __grid__ = grid;
Output
Press Run to see the output.

Bigger Grids

You can make grids as large as 200x200! Try making a bigger pattern:

javascript
let grid = [];
for (let row = 0; row < 20; row++) {
let line = [];
for (let col = 0; col < 20; col++) {
if (row < 7) {
line.push("red");
} else if (row < 14) {
line.push("white");
} else {
line.push("green");
}
}
grid.push(line);
}

let __grid__ = grid;
console.log("Italian flag!");
Output
Press Run to see the output.

Now try the exercises to create your own pixel art!