flauwekeul / honeycomb

Create hex grids easily, in node or the browser.
https://abbekeultjes.nl/honeycomb
MIT License
639 stars 59 forks source link

Simple Svelte and React Examples #118

Open johnathanludwig opened 2 months ago

johnathanludwig commented 2 months ago

Hi, I've been using this package and it has been great. I just wanted to provide a simple svelte and react examples in case you wanted to add more generic examples to the recipe documentation.

Svelte

https://svelte.dev/repl/61514fb55a1b40be84cd731028435498?version=4.2.19

<script>
    import { defineHex, Grid, rectangle } from 'honeycomb-grid'

    const Hex = defineHex({ dimensions: 30, origin: 'topLeft' })
    const grid = new Grid(Hex, rectangle({ width: 8, height: 5 }))
</script>

<svg viewBox="-1 0 500 500">
  {#each grid as hex}
        <polygon 
            points={hex.corners.map(({ x, y }) => `${x},${y}`)}
            stroke-width="1"
            stroke="#000"
            fill="none"
            />
    {/each}
</svg>

React

https://stackblitz.com/edit/vitejs-vite-evbazp?file=src%2FApp.tsx

import { defineHex, Grid, rectangle } from 'honeycomb-grid';

const Hex = defineHex({ dimensions: 30, origin: 'topLeft' });
const grid = new Grid(Hex, rectangle({ width: 8, height: 5 }));

function App() {
  return (
    <>
      <svg viewBox="-1 0 500 500">
        {grid.toArray().map((hex, index) => {
          return (
            <polygon
              key={index}
              points={hex.corners.map(({ x, y }) => `${x},${y}`).join(' ')}
              strokeWidth="1"
              stroke="#000"
              fill="none"
            />
          );
        })}
      </svg>
    </>
  );
}

export default App;
flauwekeul commented 2 months ago

Thanks. I'll consider adding these examples 👍

justinkwaugh commented 2 months ago

One thing to note is that this way of rendering is not great if you want to have any rotation of assets in a given cell. For that it is often easier to render every cell at the grid origin, rotate it and then translate it out. The current API provided is not very conducive to that though as it only will provide you points already offset from the grid origin. I've handled this by creating a single hex at 0,0 and just grabbing its points to use for every other cell, but it's a little bit annoying.

johnathanludwig commented 2 months ago

Thats true. I do something similar in my use where I want a gap between them. I use the center for positioning and doing my own calculations from there for placing the hex.

CleanShot 2024-09-17 at 14 25 59