Issue
I've made this sudoku board on Figma
and I want to put this on my website using ReactJS. My goal is to add events listeners to the rects and change the value based on user pressing 1-9 numbers (just like sudoku works). The problems is that I don't know how to programmatically position text
based on rect
(x,y) position and size.
For example:
<g x="7.49219" y="4.37108" width="34.8721" height="34.8721">
<rect
x="7.49219"
y="4.37108"
width="34.8721"
height="34.8721"
rx="4.75"
stroke="#D5D5D5"
stroke-width="0.5"
/>
<text id="text_test" fill="red" fontSize={24}>
5
</text>
</g>
I've calculated the text position as
x = rectXPos + (rectWidth / 2)
y = rectYPos + (rectHeight / 2)
but it gives me:
I thought considering the text width and height in the formula to center it. But I just get the text size in pixels on the browser
So when I try to update the formula to
x = rectXPos + (rectWidth / 2) - (textWidth / 2)
y = rectYPos + (rectHeight / 2) + (textHeight / 2)
I get this:
The X position works but the Y don't.
- What am I missing?
- Is there a better way to implement what I want?
Solution
You can rearrange the text element with the attributes text-anchor="middle"
and dominant-baseline="middle"
and set the position the middle of the expected "frame". So, in this case the <rect>
and the <text>
have the same starting point. The <rect>
is 40x40 and then the <text>
needs to be in 20,20.
You can see from the example that you can use <g>
and its attribute transform/translate to move around the elements. This gives mush more readable code now that you have 9x9 elements that need to be placed.
If this is going to be used in a browser I will suggest you to use CSS for styling. Like replace the attribute stroke
etc. with a stylesheet like:
svg.sudoku rect {
stoke: #D5D5D5;
stroke-width: .5px;
}
<svg viewBox="0 0 200 200">
<g transform="translate(5 5)">
<g transform="translate(0 0)">
<rect
width="40"
height="40"
rx="4.75"
stroke="#D5D5D5"
stroke-width="0.5"
fill="none"
/>
<text x="20" y="20" text-anchor="middle" dominant-baseline="middle" fill="red" font-size="20">5</text>
</g>
<g transform="translate(45 0)">
<rect
width="40"
height="40"
rx="4.75"
stroke="#D5D5D5"
stroke-width="0.5"
fill="none"
/>
<text x="20" y="20" text-anchor="middle" dominant-baseline="middle" fill="red" font-size="20">2</text>
</g>
</g>
</svg>
Answered By - chrwahl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.