Reputation: 794
I'm creating a RPG table game, using React-Konva. I did a infinite grid and some images tokens with drag and drop.
So, its working fine. But, looking for another feature I found this using Canvas, its almost same I did, but with spap, the shapes are attracted to the Rect as a magnetic!
Here a example:
Snap with Canvas
Snap with Konva.js
for (var i = 0; i < (600 / grid); i++) {
canvas.add(new fabric.Line([ i * grid, 0, i * grid, 600], { stroke: '#ccc', selectable: false }));
canvas.add(new fabric.Line([ 0, i * grid, 600, i * grid], { stroke: '#ccc', selectable: false }))
}
There is a way to do same with React-Konva? I Found something similar with Konva.js
EDITED:
I'm almost there!!!
const [x, setX] = useState(50)
const [y, setY] = useState(50)
const grid = 70
const gridWidth = 1100
const linesA = []
const linesB = []
for (let i = 0; i < gridWidth / grid; i++) {
linesA.push(
<Line
strokeWidth={2}
stroke={'black'}
points={[i * grid, 0, i * grid, gridWidth]}
/>
)
linesB.push(
<Line
strokeWidth={2}
stroke={'black'}
points={[0, i * grid, gridWidth, i * grid]}
/>
)
}
<Layer>
{linesA}
{linesB}
</Layer>
I made the grid with lines, now I'm a little confuse about the dragEnd event X, Y.
MY RECT
<Rect
onDragEnd={e => {
e.target.to({
x: Math.round(x / grid) * grid,
y: Math.round(y / grid) * grid,
})
}}
x={x}
y={y}
draggable
width={60}
height={60}
fill="rgba(0, 0, 0, 1)"
/>
Its really almost there.
Upvotes: 3
Views: 4775
Reputation: 794
Its Done! I will post my own answer to help out someone.
const grid = 70
const gridWidth = 1000
const linesA = []
const linesB = []
for (let i = 0; i < gridWidth / grid; i++) {
linesA.push(
<Line
strokeWidth={2}
stroke={'black'}
points={[i * grid, 0, i * grid, gridWidth]}
/>
)
linesB.push(
<Line
strokeWidth={2}
stroke={'black'}
points={[0, i * grid, gridWidth, i * grid]}
/>
)
}
<Stage
x={stagePos.x}
y={stagePos.y}
width={window.innerWidth}
height={window.innerHeight}
draggable
onDragEnd={e => {
setStagePos(e.currentTarget.position())
}}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseMove={handleMouseMove}
onContextMenu={e => {
e.evt.preventDefault()
}}
>
{/* <Layer>
<Image image={map} opacity={1} />
</Layer> */}
<Layer>
{linesA}
{linesB}
</Layer>
<Rect
onDragEnd={e => {
e.target.to({
x: Math.round(e.target.x() / grid) * grid,
y: Math.round(e.target.y() / grid) * grid,
})
}}
x={x}
y={y}
draggable
width={65}
height={65}
fill="rgba(0, 0, 0, 1)"
/>
</Stage>
Here I did a live example! Snap Grid React-Konva
Upvotes: 9