Search code examples
javascriptcssreactjscreate-react-app

images not being in their right position when using grid


I have 3 component files and a CSS one, but for some reason, Tiles are moving a little bit to the top left.

it's not giving me any error but when I use the view grid feature in firefox, it appears that tiles aren't in the cells, and the Tile on the top left corner appears smaller than every other tile

here is the code:

App.jsx:

import React from 'react';
import tilesPacked from './assets/Tilemap/tiles_packed.png';
import mapjson from './assets/map.json';
import { Map } from './components/map.jsx';

export default function App() {
    let root = document.querySelector(':root');
    root.style.setProperty(
        '--factor',
        (window.innerWidth / 64 / 16 + window.innerHeight / 32 / 16) / 2
    );
    return (
        <div className="App">
            <Map src={tilesPacked} json={mapjson} className="map" />
        </div>
    );
}

map.jsx:

import react from 'react';
import { Tile } from './tile.jsx';

export class Map extends react.Component {
    render() {
        return (
            <div className="Map">
                {this.props.json.layers[0].data.map((tile, i) => {
                    return (
                            <Tile
                                key={i}
                                src={this.props.src}
                                x={tile % 12}
                                y={Math.floor(tile / 12)}
                            />
                    );
                })}
            </div>
        );
    }
}

tile.jsx:

import React from 'react';

export class Tile extends React.Component {
    render() {
        return (
            <img
                src={this.props.src}
                alt=""
                className={`tile${this.props.aClass ? ' ' + this.props.aClass : ''}`}
                style={{
                    objectPosition: `${(this.props.x - 1) * -16}px ${this.props.y * -16}px`,
                }}
            />
        );
    }
}

index.css:

:root {
    --factor: 4;
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.tile {
    height: 16px;
    width: 16px;
    object-fit: none;
    transform: scale(var(--factor));
    image-rendering: pixelated;
}
.Map {
    display: grid;
    grid-template-columns: repeat(64, calc(var(--factor) * 16px));
    grid-template-rows: repeat(32, calc(var(--factor) * 16px));
}
body{
    overflow: hidden;
    width: 100%;
    height: 100%;
}

Solution

  • after thinking, the whole problem was because I didn't set the transform-origin property to top left, it's by default center, which makes it not as I expected