DEV Community

Cover image for Draw a pixel art with vanilla js
Lam
Lam

Posted on

Draw a pixel art with vanilla js

Hi there, I'm a frontend developer and learning to become a game developer, I very stuck when searching art, and sprites for my game so I decided to draw them with my experience on javascript :D here are my work (It's very simple):

Prepare a canvas element

<div style="width: 100vw;height: 100vh;display: flex;justify-content: center;align-items: center;">
  <div>
    <canvas id="canvas" width="512" height="512" style="width: 512px; height: 512px"></canvas>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Data:

Color schema

[
    "#c6bfbe",
    "#040309",
    "#e0e6e9",
    "#9d919d",
    "#b0813f",
    "#cf7f33",
    "#adb6b1",
    "#1d1f29"
]
Enter fullscreen mode Exit fullscreen mode

Pixel maping:

{
    "2_3": 1,
    "2_4": 1,
    "2_5": 1,
    "2_6": 1,
    "2_8": 1,
    "2_9": 1,
    "3_3": 1,
    "3_4": 3,
    "3_5": 1,
    "3_6": 4,
    "3_7": 1,
    "3_8": 6,
    "3_9": 0,
    "4_2": 1,
    .....
}
Enter fullscreen mode Exit fullscreen mode

And code to drawl pixel

const canvas = document.getElementById("canvas");
  const baseSize = Math.round(canvas.width / size)
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "#F0F0F0";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  for (const key in data) {
    const [x, y] = key.split("_")
    ctx.fillStyle = colors[data[key]];
    ctx.fillRect(+x * baseSize, +y * baseSize, baseSize, baseSize);
}
Enter fullscreen mode Exit fullscreen mode

Tada! It's results:

Duck pixel art

You can get more pixel art data by inspecting API from simplepixelart.com. I welcome that!

Full source code at:

Top comments (1)

Collapse
 
christianpaez profile image
Christian Paez

nicee