2

I'm trying to implement a board game in React. I'm using area/map tags to detect clicks on the board. I want to place a prick/stone on the position of the area tag, when some logic happens. How can I place an img element on the position of the area tag in the board-img element?

I've tried this code, but it dosen't seem to work..

renderBoard() {
    const board = this.state.gameState.board;
    let positionSyle = {};
    let square = this['w1'] ? this['w1'].getBoundingClientRect() : false;
    if (square) {
        {/**Find square w1 and get position its position */ }
        positionSyle = {
            top: square.top + 'px',
            left: square.left + 'px',
        }
    }
    return (
        <React.Fragment>
            {/**render board image + insert areas on board(squares) */}

            <div>
                <img src="board.png" useMap="#image-map" />
                <map name="image-map">
                    <area ref={(c) => this['w1'] = c} target alt="w1" title="w1" coords="387,313,315,244" shape="rect" onClick={() => console.log('w1')} />
                    <area ref={(c) => this['w2'] = c} target alt="w2" title="w2" href coords="295,317,219,243" shape="rect" onClick={() => console.log('w2')} />
                </map>

                <img src={"w-stone.png"} style={{ ...positionSyle, position: 'absolute', width: '50px', height: '50px' }} />
            </div>

        </React.Fragment>

    )
}

Screenshot of current code. The stone should be placed on the "w1" square. But it isn't..

enter image description here

j08691
  • 204,283
  • 31
  • 260
  • 272
YousefM
  • 185
  • 9
  • 1
    Just curious, why did you opt for area/map tags instead of attaching `onclick` listeners to each element that's interactive? – Keno Mar 11 '19 at 15:15
  • https://stackoverflow.com/questions/1906734/visible-area-tag – Paulie_D Mar 11 '19 at 15:23
  • Area tags aren't DOM elements so it's unlikely you would select one with JS....but my expertise here is limited. – Paulie_D Mar 11 '19 at 15:24
  • @Paulie_D Thanx for your answer. "Unfortunately" I think that you're right:/ – YousefM Mar 11 '19 at 16:14
  • 1
    The more optimal solution would be to cut out the sections of the image to be seperate images for each board piece, and then use those as background images to `div`s for example. – Keno Mar 11 '19 at 17:32
  • 1
    I found a .png to .svg converter(https://www.vectorizer.io/). That I think would make me able to solve the problem. Anyway your suggestion would also solve the problem, @KenoClayton. – YousefM Mar 11 '19 at 18:21

0 Answers0