An isometric building in SVG, drawn in code with React

Draw an isometric building in React with a tiny projection function: boxes to faces, a battery filled to its charge, power flowing along cables and labels on dotted leaders.

7 min read

The real component. Click the picture to open it live and try it before you read how it was built.

Isometric drawings look complex, but they come from one small function. Our energy page draws a whole building that way.

One projection function

A point in the building's space (x, y, z) maps to the screen by shifting right for x minus y, down for x plus y, and up for z. Everything else is built on that.

src/registry/landing-pages/wattline/iso.ts

// Isometric drawing helpers for the building diagram: a point in the building's own units (x along one side, y along
// the other, z up) projected onto the 900 × 440 drawing.
const ORIGIN = { x: 430, y: 200 };
const COS30 = 0.866;

export type Point = [number, number, number];

export function iso([x, y, z]: Point): [number, number] {
  return [ORIGIN.x + (x - y) * COS30, ORIGIN.y + (x + y) * 0.5 - z];
}

// An SVG points string for a polygon through these building points.
export function poly(points: Point[]): string {
  return points.map((point) => iso(point).join(",")).join(" ");
}

export interface Box {
  x: [number, number];
  y: [number, number];
  z: [number, number];
}

// The three faces of a box the viewer can see: its top, the face toward +x and the face toward +y.
export function facesOf({ x: [x0, x1], y: [y0, y1], z: [z0, z1] }: Box) {
  return {
    top: poly([
      [x0, y0, z1],
      [x1, y0, z1],
      [x1, y1, z1],
      [x0, y1, z1],
    ]),
    right: poly([
      [x1, y0, z0],
      [x1, y1, z0],
      [x1, y1, z1],
      [x1, y0, z1],
    ]),
    front: poly([
      [x0, y1, z0],
      [x1, y1, z0],
      [x1, y1, z1],
      [x0, y1, z1],
    ]),
  };
}

// A path string through building points.
export function pathOf(points: Point[]): string {
  return points.map((point, index) => `${index === 0 ? "M" : "L"} ${iso(point).join(" ")}`).join(" ");
}
Projection, polygons and the three visible faces of a box

Boxes become faces

A box has three visible faces from this angle: top, right and front. Give each a slightly different shade and you have depth without lighting. The building, the HVAC unit, the battery and the meter are all boxes.

src/registry/landing-pages/wattline/building-parts.tsx

import { facesOf, pathOf, poly, type Box } from "./iso";

export const BUILDING: Box = { x: [0, 200], y: [0, 150], z: [0, 150] };
export const HVAC: Box = { x: [128, 186], y: [108, 140], z: [150, 172] };
export const BATTERY: Box = { x: [262, 322], y: [36, 96], z: [0, 92] };
export const METER: Box = { x: [36, 70], y: [196, 222], z: [0, 58] };

const FLOORS = [30, 60, 90, 120];
const MULLIONS = [25, 50, 75, 100, 125, 150, 175];
const PANEL_COLS = [16, 54, 92, 130, 168];
const PANEL_ROWS = [14, 44, 74];

// A box drawn as three lit faces: the top brightest, the two sides a step darker each.
export function IsoBox({
  box,
  top = "fill-white",
  right = "fill-zinc-50",
  front = "fill-zinc-100",
}: {
  box: Box;
  top?: string;
  right?: string;
  front?: string;
}) {
  const faces = facesOf(box);
  return (
    <g className="stroke-zinc-400" strokeWidth={1} strokeLinejoin="round">
      <polygon points={faces.right} className={right} />
      <polygon points={faces.front} className={front} />
      <polygon points={faces.top} className={top} />
    </g>
  );
}

// The building: its box, floor lines and window mullions on both visible faces, and solar panels across the roof.
export function Building() {
  const [x0, x1] = BUILDING.x;
  const [y0, y1] = BUILDING.y;
  const roof = BUILDING.z[1];
  return (
    <g>
      <IsoBox box={BUILDING} />
      <g className="stroke-zinc-300" strokeWidth={0.75}>
        {FLOORS.map((z) => (
          <path
            key={`f${z}`}
            d={`${pathOf([
              [x1, y0, z],
              [x1, y1, z],
            ])} ${pathOf([
              [x0, y1, z],
              [x1, y1, z],
            ])}`}
            fill="none"
          />
        ))}
        {MULLIONS.filter((x) => x < x1).map((x) => (
          <path
            key={`m${x}`}
            d={pathOf([
              [x, y1, 0],
              [x, y1, roof],
            ])}
          />
        ))}
        {MULLIONS.filter((y) => y < y1).map((y) => (
          <path
            key={`n${y}`}
            d={pathOf([
              [x1, y, 0],
              [x1, y, roof],
            ])}
          />
        ))}
      </g>
      <g className="fill-zinc-100 stroke-zinc-400" strokeWidth={0.75}>
        {PANEL_ROWS.flatMap((y) =>
          PANEL_COLS.map((x) => (
            <polygon
              key={`${x}-${y}`}
              points={poly([
                [x, y, roof],
                [x + 32, y, roof],
                [x + 32, y + 24, roof],
                [x, y + 24, roof],
              ])}
            />
          )),
        )}
      </g>
      <IsoBox box={HVAC} />
    </g>
  );
}

// The battery: a box whose two visible faces fill with the accent up to its charge.
export function Battery({ percent }: { percent: number }) {
  const [x0, x1] = BATTERY.x;
  const [y0, y1] = BATTERY.y;
  const level = BATTERY.z[0] + ((BATTERY.z[1] - BATTERY.z[0]) * percent) / 100;
  return (
    <g>
      <IsoBox box={BATTERY} />
      <g className="fill-lime-300 stroke-lime-500" strokeWidth={0.75}>
        <polygon
          points={poly([
            [x1, y0, 0],
            [x1, y1, 0],
            [x1, y1, level],
            [x1, y0, level],
          ])}
        />
        <polygon
          points={poly([
            [x0, y1, 0],
            [x1, y1, 0],
            [x1, y1, level],
            [x0, y1, level],
          ])}
        />
      </g>
      <path
        d={pathOf([
          [x1, y0, level],
          [x1, y1, level],
          [x0, y1, level],
        ])}
        fill="none"
        className="stroke-lime-600"
        strokeWidth={1.25}
      />
    </g>
  );
}
The parts: building, battery filled to its charge

Things that move

Power flows along the cables as a dashed stroke whose offset animates, and stays still with reduced motion. Readings sit in labels joined to their part by dotted leaders with small square anchors.

src/registry/landing-pages/wattline/building-diagram.tsx

"use client";

import { motion } from "motion/react";
import { usePrefersReducedMotion } from "@/hooks/use-prefers-reduced-motion";
import { BATTERY, BUILDING, Battery, Building, HVAC, IsoBox, METER } from "./building-parts";
import { iso, pathOf, poly, type Point } from "./iso";
import type { Reading } from "./types";

// Where each reading's connector lands on the drawing, and where its label sits.
const ANCHORS: Record<Reading["target"], { at: Point; label: [number, number] }> = {
  solar: { at: [90, 40, 150], label: [10, 60] },
  hvac: { at: [186, 124, 172], label: [700, 86] },
  battery: { at: [322, 66, 70], label: [700, 236] },
  grid: { at: [36, 209, 58], label: [10, 300] },
};
const LABEL = { width: 190, height: 54 };
const GROUND: Point[] = [
  [-40, -30, 0],
  [350, -30, 0],
  [350, 250, 0],
  [-40, 250, 0],
];
// Cables on the ground: battery to building, and meter to building.
const BATTERY_CABLE: Point[] = [
  [BATTERY.x[0], 66, 0],
  [BUILDING.x[1], 66, 0],
];
const GRID_CABLE: Point[] = [
  [53, METER.y[0], 0],
  [53, BUILDING.y[1], 0],
];

// A live reading in a small bordered label, joined to its part of the building by a dotted line.
function ReadingLabel({ reading }: { reading: Reading }) {
  const { at, label } = ANCHORS[reading.target];
  const [ax, ay] = iso(at);
  const [lx, ly] = label;
  const edgeX = lx < ax ? lx + LABEL.width : lx;
  return (
    <g>
      <path
        d={`M ${ax} ${ay} L ${edgeX} ${ly + LABEL.height / 2}`}
        fill="none"
        className="stroke-zinc-400"
        strokeWidth={1}
        strokeDasharray="2 4"
      />
      <rect x={ax - 3} y={ay - 3} width={6} height={6} className="fill-zinc-950" />
      <rect x={lx} y={ly} width={LABEL.width} height={LABEL.height} rx={6} className="fill-white stroke-zinc-300" />
      <text x={lx + 12} y={ly + 18} fontSize={11} className="fill-zinc-500 font-mono">
        {reading.key.toUpperCase()}
      </text>
      <text x={lx + 12} y={ly + 34} fontSize={13} className="fill-zinc-950 font-mono font-medium">
        {reading.value}
      </text>
    </g>
  );
}

// Power moving along a cable: dashes that travel from source to building, still for reduced motion.
function Flow({ points, className }: { points: Point[]; className: string }) {
  const isStill = usePrefersReducedMotion();
  return (
    <motion.path
      d={pathOf(points)}
      fill="none"
      strokeWidth={2.5}
      strokeLinecap="round"
      strokeDasharray="4 8"
      className={className}
      animate={isStill ? undefined : { strokeDashoffset: [0, -24] }}
      transition={{ duration: 0.9, repeat: Infinity, ease: "linear" }}
    />
  );
}

interface BuildingDiagramProps {
  readings: Reading[];
  batteryPercent: number;
}

// One customer building drawn in isometric line work: the solar roof and the HVAC unit on it, the battery filling to
// its charge, the grid meter, the cables between them carrying power, and every live reading labelled at its part.
export function BuildingDiagram({ readings, batteryPercent }: BuildingDiagramProps) {
  return (
    <svg
      viewBox="0 30 900 380"
      className="h-auto w-full"
      role="img"
      aria-label={`Building diagram: ${readings.map((reading) => `${reading.key} ${reading.value}`).join(", ")}`}
    >
      <polygon points={poly(GROUND)} className="fill-zinc-50/60 stroke-zinc-300" strokeDasharray="3 5" />
      <path d={pathOf(BATTERY_CABLE)} className="stroke-zinc-300" strokeWidth={4} strokeLinecap="round" />
      <path d={pathOf(GRID_CABLE)} className="stroke-zinc-300" strokeWidth={4} strokeLinecap="round" />
      <Flow points={BATTERY_CABLE} className="stroke-lime-500" />
      <Flow points={[...GRID_CABLE].reverse()} className="stroke-zinc-500" />
      <IsoBox box={METER} />
      <Building />
      <Battery percent={batteryPercent} />
      <IsoBox
        box={{
          x: [HVAC.x[0] + 8, HVAC.x[0] + 24],
          y: [HVAC.y[0] + 8, HVAC.y[0] + 24],
          z: [HVAC.z[1], HVAC.z[1] + 3],
        }}
        top="fill-zinc-300"
      />
      {readings.map((reading) => (
        <ReadingLabel key={reading.key} reading={reading} />
      ))}
    </svg>
  );
}
The diagram

More articles