DEV Community

This is Football 247
This is Football 247

Posted on

Building a Drag-and-Drop Football Lineup Builder with SVG and Vanilla JavaScript

Every football fan has picked an all-time XI in their head. Plenty of Sunday league managers still write their team sheet on the back of an envelope. I wanted a tool for both: pick a formation, drag players around a pitch, then download the lineup as an image or print it for the dressing room.

I built it as a free football formation creator that runs entirely in the browser: no framework, no backend, no sign-up. It's a single WordPress shortcode that outputs HTML, CSS and plain JavaScript. Here are the parts that were more interesting than I expected.

Turning "4-2-3-1" into positions on a pitch

Every formation is just a string. Split it on the dashes and you get the rows, from defence to attack:

const rows = f => f.split('-').map(Number); // "4-2-3-1" -> [4, 2, 3, 1]
Enter fullscreen mode Exit fullscreen mode

The goalkeeper always sits at the bottom. Every other row is spaced evenly between a "back line" and a "front line", and the players in each row are spaced evenly across the pitch:

function basePositions(formation) {
  const r = rows(formation), n = r.length;
  const pos = [[300, GK_Y]];                      // goalkeeper first
  const top = n >= 4 ? 156 : n === 3 ? 176 : 216; // fewer rows, less spread
  const bottom = 561;
  r.forEach((count, i) => {
    const y = n === 1 ? (top + bottom) / 2 : bottom - i * (bottom - top) / (n - 1);
    for (let j = 0; j < count; j++) {
      pos.push([60 + (j + 0.5) * 480 / count, y]); // centre each player in his slot
    }
  });
  return pos;
}
Enter fullscreen mode Exit fullscreen mode

That one function handles every formation I support: 13 for 11-a-side and 16 across 5, 6 and 7-a-side. A diamond like 4-1-2-1-2 comes out right with no special cases, because single-player rows are centred automatically.

The "top" line moves down when there are fewer rows. Without that, a 5-a-side 2-2 spreads the two pairs across the whole pitch and looks silly.

Naming positions without a lookup table

The tool can show position labels on the shirts (LB, CB, DM, ST and so on). I didn't want a hand-written map for 29 formations, so the labels come from a few rules:

  • The first row is the defence. Four players are LB, CB, CB, RB. Five are LWB, CB, CB, CB, RWB.
  • The last row is the attack. One player is ST, two are ST and ST, three are LW, ST and RW.
  • Everything in between is midfield. With four or more rows, the first midfield row is defensive (DM) and the last is attacking (AM), so 4-2-3-1 becomes DM, DM, then LW, AM, RW.

It isn't perfect for every exotic shape, but it's right for every formation people actually pick.

Shirts with SVG clipPath

Each player is an SVG group: a shirt, a number and a name. The shirt is one path, and the patterns (stripes, hoops, halves, a sash, contrast sleeves) are plain rectangles clipped to that path:

<defs>
  <clipPath id="shirt">
    <path d="M-10,-24 L-22,-19 L-29,-4 L-19,1 L-17,-5 L-17,24 L17,24 L17,-5 L19,1 L29,-4 L22,-19 L10,-24 Q0,-15 -10,-24 Z"/>
  </clipPath>
</defs>

<g transform="translate(300,400)">
  <g clip-path="url(#shirt)">
    <rect x="-30" y="-30" width="60" height="60" fill="#d62828"/>
    <!-- stripes: secondary-colour rects, clipped to the shirt -->
    <rect x="-12" y="-30" width="6" height="60" fill="#ffffff"/>
    <rect x="-1"  y="-30" width="6" height="60" fill="#ffffff"/>
    <rect x="10"  y="-30" width="6" height="60" fill="#ffffff"/>
  </g>
</g>
Enter fullscreen mode Exit fullscreen mode

Because the clip path is defined once in user space and every player group is translated, one clipPath serves all 11 shirts.

A detail that mattered: white numbers on white stripes vanish. Giving the number text a dark stroke with paint-order="stroke" draws the outline behind the fill, so the number stays readable on any kit.

Drag and drop that works on a phone

Most visitors are on mobile, so dragging had to work with a thumb. Pointer events handle mouse and touch in one code path. The key is converting screen coordinates into SVG coordinates with the SVG's own transform matrix, which works at any zoom level:

function toSvg(svg, e) {
  const p = svg.createSVGPoint();
  p.x = e.clientX;
  p.y = e.clientY;
  return p.matrixTransform(svg.getScreenCTM().inverse());
}
Enter fullscreen mode Exit fullscreen mode

Two small things made it feel right:

  1. Tap versus drag. If the pointer moves less than 5 pixels between down and up, it counts as a tap and opens that player's name field instead of moving him.
  2. Scrolling. The shirts get touch-action: none and a non-passive touchstart handler that calls preventDefault(), so dragging a player doesn't scroll the page. The rest of the pitch still scrolls normally.

Exporting a PNG without html2canvas

The download button doesn't screenshot the page. It builds a clean SVG string of the lineup, without the "tap to edit" placeholders, then draws it onto a canvas:

function svgToPng(svgString, width, height, scale, done) {
  const img = new Image();
  img.onload = () => {
    const canvas = document.createElement('canvas');
    canvas.width = width * scale;
    canvas.height = height * scale;
    const ctx = canvas.getContext('2d');
    ctx.scale(scale, scale);
    ctx.drawImage(img, 0, 0, width, height);
    canvas.toBlob(done);
  };
  img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgString);
}
Enter fullscreen mode Exit fullscreen mode

Drawing at 2x gives a sharp image on retina screens. The export is portrait (4:5), which is the tallest ratio most social feeds show without cropping.

The same trick produces the printable A4 team sheet. It's one large SVG with the match details, the pitch nested inside it as its own <svg> with a viewBox, the starting lineup, subs and notes. Nesting meant I could reuse the exact pitch-drawing function at a different size with no changes.

Share links with no database

There's no backend, so the share link carries the entire lineup in the URL hash: formation, kit colours, names, numbers, custom positions and captain. The state is JSON-encoded and turned into URL-safe base64:

function encode(state) {
  const utf8 = unescape(encodeURIComponent(JSON.stringify(state)));
  return btoa(utf8).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
Enter fullscreen mode Exit fullscreen mode

The encodeURIComponent and unescape pair matters, because plain btoa throws on accented names like Ødegaard. Opening the link decodes the hash and restores the lineup, and the person can carry on editing it.

The current lineup also saves to localStorage after every change, wrapped in try/catch because some private browsing modes throw when you touch storage.

What I'd do differently

  • Start with mobile. I designed on desktop first and then rebuilt the layout for phones. Most people use it on a phone, so I should have started there.
  • Keep one source of truth for geometry. The pitch, the drag maths, the image export and the team sheet all read from the same coordinate system, which is why nesting and reuse were so easy. I'd do that from day one again.
  • Design the export as a product. The downloaded image is what actually gets shared, so it deserves as much care as the tool.

You can try the formation creator for free on This Is Football 247, along with a few other football tools I've built. I'd love to hear how you'd handle formations I haven't thought of.

Top comments (0)