DEV Community

Michael Burrows
Michael Burrows

Posted on • Edited on • Originally published at w3collective.com

Design & animate a pseudo 3D “Super Mario” with Zdog

[CodePen Demo | Original Article]

I recently stumbled upon Zdog a 3D JavaScript engine for rendering simple 3D models on the Web.

After playing around with the basic concepts I thought I’d attempt to design an 8-bit style Super Mario.

To get started quickly I just installed Zdog via CDN but it's also available as a download and NPM.

<script src="https://unpkg.com/zdog@1/dist/zdog.dist.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Once Zdog was installed I created the <canvas> HTML element:

<canvas class="zdog-canvas" width="300" height="300"></canvas>
Enter fullscreen mode Exit fullscreen mode

Next a new illustration was created that will render the final design to the zdog-canvas:

let illo = new Zdog.Illustration({
  element: ".zdog-canvas" 
});
illo.updateRenderGraph();
Enter fullscreen mode Exit fullscreen mode

Here’s how a single box is created in Zdog:

new Zdog.Box({
  addTo: illo,
  width: 10,
  height: 10,
  depth: 10,
  stroke: false,
  color: "#000",
  translate: { x: 0, y: 0 },
});
Enter fullscreen mode Exit fullscreen mode

To create Mario I’ll need to create a series of boxes in different colors and position them via their x & y axis.

Here’s an image that shows each of the boxes (pixels) required for Mario:

Alt Text

In total there are 144 boxes with 7 colors that will need to be rendered.

I setup variables for each of the colors:

const red = "#ff0000";
const blue = "#001cff";
const yellow = "#fffe00";
const black = "#000000";
const skin = "#ffaa7d";
const hair = "#340d00";
const shoe = "#5d2914";
Enter fullscreen mode Exit fullscreen mode

Then created an array to store objects with the values for each box:

const mario = [
  // column 1
  { x: -60, y: 10, color: blue },
  { x: -60, y: 20, color: skin },
  { x: -60, y: 30, color: skin },
  { x: -60, y: 40, color: skin },
  { x: -60, y: 70, color: shoe },
];
Enter fullscreen mode Exit fullscreen mode

This is for the first column, in total there are 12 columns (view full code here).

I can now loop over each object adding a 10x10x10 box with the defined color, x & y values to the illustration:

mario.forEach(function (block) {
  new Zdog.Box({
    addTo: illo,
    width: 10,
    height: 10,
    depth: 10,
    stroke: false,
    color: block.color,
    translate: { x: block.x, y: block.y },
  });
});
Enter fullscreen mode Exit fullscreen mode

Here’s what Mario looks like at this stage:

Alt Text

To complete the design I added some animation so Mario rotates 360 degrees:

function animate() {
  illo.rotate.y += isSpinning ? 0.05 : 0;
  illo.updateRenderGraph();
  requestAnimationFrame(animate);
}
animate();
Enter fullscreen mode Exit fullscreen mode

Alt Text

Hopefully this sparked your interest in Zdog – stay tuned for more tutorials in the future.

Top comments (0)