Stop dragging once connected - react-konva

I am using React-Konva library for creating shapes using my palette. Then I am dragging it to connect. But once it is connected it should then draggable for group should only work not for each item.
I have put different shapes inside a variable globally in const.
const shapes=
<Group
draggable
>
<Shape
sceneFunc={(context, shape) => {
context.beginPath();
context.moveTo(300, 100);
context.lineTo(300, 100);
context.quadraticCurveTo(150, 100, 100, 100);
context.closePath();
context.fillStrokeShape(shape);
}}
fill="#eff0f1"
stroke="#222"
/>
<Circle
x={305}
y={100}
radius={10}
fill="#eff0f1"
stroke="#222"
/>
</Group>
const block=<Rect
x={2}
y={170}
width={100}
height={100}
draggable
fill="#eff0f1"
stroke="#222"
/>
Now once it I check the palette button I push variable inside an array but once the connector of shape variable touches reactangle then it should be joined as a single element or grouped
<Stage width={950} height={585}>
<Layer>
<Group draggable>
{connector && multiConnector.map(shape=>{
return shape;
})}
{rect && multiBlock.map(block=>{
return block;
})}
</Group>
</Layer>
</Stage>
constructor(){
super();
this.state={
connector:false,
rect:false,
multiBlock:[],
multiConnector:[]
}
}
showConnector=() =>{
const { multiConnector } = this.state;
multiConnector.push(shapes);
this.setState({connector:true, multiConnector:multiConnector});
}
showRect=()=>{
const { multiBlock } = this.state;
multiBlock.push(block);
this.setState({rect:true, multiBlock:multiBlock});
}
First the connector means shapes should not cross rectangle or cannot go inside the boundary of rectangle.
Once connected then individual shapes or rectangle should not move rather move collectively like a group

Related

How to center items inside konvajs?

I am currently building some sort of meme-editor in react and for that I am using konvajs to function similar to a Canvas.
My problem is that I am unable to center the items inside the canva stage, as there seems to be some property that just overrides my styling.
This is (part of) the return statement in my react-component:
<div className="mycanvas">
<Stage width={500} height={500} className="stage">
<Layer>
<Image image={image} className="meme" />
{textFields.map((text) => (
<Text
text={text}
draggable
fontFamily="Impact"
fontSize="30"
stroke="white"
/>
))}
</Layer>
</Stage>
</div>
And this is how the output gets rendered.
I have coloured the background of the wrapper blue, to show in which box the image should be centered.
I have already tried CSS on the classes "mycanvas", "stage" and "meme" and also on "konvajs-content" (as that showed up in my inspector for some reason). I have used align-items: center, margin: auto and a couple others, but I think normal CSS does not really apply here.
I think it is an issue regarding the generaly styling of konvajs components, but unfortunately I could not find any solution on stackoverflow or the konva documentation.
This is an instance where CSS can't help. When the image is applied to the canvas using its height and width at the x and y coordinates you supply, the pixels of the image become part of the rasterized canvas. In other words, the image doesn't exist independent of the canvas.
Therefore, if you want to center the image inside of your canvas, you need to do a little math to calculate the x and y coordinates that will place the image centered inside the canvas.
Demo
For example, if your canvas size is 500px tall and your image has a height of 350px, then you need to set the y position to 75px (i.e., (500 - 350) / 2).
The demo code below shows how to replicate the behavior of CSS object-fit: contain. This will adjust the image to fill the canvas in one direction, and then center the image in the other direction.
import { useState, useEffect } from "react";
import { Stage, Layer, Image, Text } from "react-konva";
function Example() {
const w = window.innerWidth;
const h = window.innerHeight;
const src = "https://konvajs.org/assets/yoda.jpg";
const [image, setImage] = useState(null);
const [pos, setPos] = useState({ x: 0, y: 0 });
useEffect(() => {
const image = new window.Image();
image.src = src;
image.addEventListener("load", handleLoad);
function handleLoad(event) {
const image = event.currentTarget;
/* after the image is loaded, you can get it's dimensions */
const imgNaturalWidth = image.width;
const imgNaturalHeight = image.height;
/*
calculate the horizontal and vertical ratio of the
image dimensions versus the canvas dimensions
*/
const hRatio = w / imgNaturalWidth;
const vRatio = h / imgNaturalHeight;
/*
to replicate the CSS Object-Fit "contain" behavior,
choose the smaller of the horizontal and vertical
ratios
if you want a "cover" behavior, use Math.max to
choose the larger of the two ratios instead
*/
const ratio = Math.min(hRatio, vRatio);
/*
scale the image to fit the canvas
*/
image.width = imgNaturalWidth * ratio;
image.height = imgNaturalHeight * ratio;
/*
calculate the offsets so the image is centered inside
the canvas
*/
const xOffset = (w - image.width) / 2;
const yOffset = (h - image.height) / 2;
setPos({
x: xOffset,
y: yOffset
});
setImage(image);
}
return () => {
image.removeEventListener("load", handleLoad);
};
}, [src, h, w]);
return (
<Stage width={w} height={h} style={{ background: "black" }}>
<Layer>
<Image x={pos.x} y={pos.y} image={image} />
<Text
text="I am centered"
fontFamily="Impact"
fontSize={50}
stroke="white"
strokeWidth={1}
x={pos.x}
y={pos.y}
/>
</Layer>
</Stage>
);
}

Changing react-leaflet map width with button click

I am working on a map with react-leaflet. I placed a button on the map that will ideally open a menu on the left side of the map. The way I want to open up the menu is by changing the width of the map from 100% to 80%. The menu button toggles a boolean, which ideally the map will rerender and resize when the button clicks.
this is the code in my App.js
export default function App() {
const [isMarkerClick, setIsMarkerClick] = React.useState(false);
const [isMenuOn, setIsMenuOn] = React.useState(false);
function toggleMarker() {
setIsMarkerClick(prevClick => !prevClick);
}
function toggleMenu() {
setIsMenuOn(prevMenu => !prevMenu);
}
return (
<div>
<MainMap isMenuOn={isMenuOn} />
<MarkerButton isMarkerClick={isMarkerClick} toggleMarker={toggleMarker} />
<MenuButton toggleMenu={toggleMenu} />
</div>
)
}
this is where the Map Code lives
export default function MainMap(props) {
const isMenuOn = props.isMenuOn;
const isMarkerClick = props.isMarkerClick;
const zoom = 15;
const position = ['39.9526', '-75.1652'];
const [marker, setMarker] = React.useState(["", ""])
return (
<div>
<MapContainer
center={position}
zoom={zoom}
zoomControl={false}
style={{
height: "100vh",
width: isMenuOn ? "80vw" : "100vw"
}}
>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={marker}></Marker>
{isMarkerClick && <ClickTrack setMarker={setMarker} />}
</MapContainer>
</div>
)
}
as of now, when I click the menu button, the isMenuOn state updates and which then feeds back into the MapContainer and should rerender with a new width but it doesn't. Any Ideas on how to get change the map size with a click of button using react?
example of the menu button
I thought that when clicking the menu button and changing the state of isMenuOn to "true", the mapcontainer would be listening and rerender with using the new width. Although it seems like setting the width through style ={{}}, might not allow for changes?
React Leaflet will only set the width and height when the component mounts and does not update it with the state changes, in order to update the map's width you need to re-render the component fully and to do that set the component's key to something that will change with the isMenuOpen value
here is an example
<MapContainer
center={position}
zoom={zoom}
zoomControl={false}
key={isMenuOn ? "open-state": "closed-state"}
style={{
height: "100vh",
width: isMenuOn ? "80vw" : "100vw"
}}
>
The accepted answer works, but I suspect it would cause a full map reload. You can try keeping the width value static in the MapContainer element, and instead change it the wrapping div like this:
<div style={{ width: isMenuOn ? '80vw' : '100vw' }}>
<MapContainer
center={position}
zoom={zoom}
zoomControl={false}
style={{
height: '100vh',
width: '100%',
}}
/>
</div>
There is a caveat though; the map needs to be informed of the change in size, otherwise it will seem buggy. I suspect that's why the developers don't update the style after the map mount.
You can however add a map child that monitors the isMenuOn prop (or any other prop that changes your layout), and let the map instance know they should invalidate everything about sizing:
function LayoutListener({ isMenuOn }) {
const map = useMap();
useEffect(() => {
map?.invalidateSize();
}, [map, isMenuOn]);
return null;
}
And then just put in the MapContainer children:
<MapContainer>
<LayoutListener isMenuOn={isMenuOn} />
{otherChildren}
</MapContainer>

How to make non-interactive Grid overlay?

I want to have the Grid visible on my site while i'm developing it, a-la Adobe XD style (link to image), to better understand how much place elements are taking(or should take).
The code underneath works but I have to manually specify Width of the grid when setting position to 'fixed' or 'absolute'.
There must be a more elegant way to do this.
Any suggestions on how to do this?
const testGridItems = () =>{
var list = new Array();
for(let i=0; i<12; i++){
list.push(
<Grid item xs={1}>
<div align='center'
style={{
height: '100vh',
position:'relative',
backgroundColor: '#F6BB42',
opacity:0.2}
}>
{i+1}
</div>
</Grid>
)
}
return list;
}
const testGrid = () => {
return (
<Grid container
style={{
width:1200,
position:'fixed'
}}
spacing={24} >
{ testGridItems() }
</Grid>
)
}

How can i scroll bottom on onPress of button in react-native?

I have added the button on simple screen and I want to scroll Bottom whenever I press the button. what code to add to button onPress?
render() {
return (
<ScrollView>
{this.yourComponents()}
<Button>Scroll To Bottom </Button>
</ScrollView>
)
}
You could do this using ref.
render() {
return (
<ScrollView ref={scrollView => this.scrollView = scrollView}>
{this.yourComponents()}
<Button onPress={() => {this.scrollView.scrollToEnd()}}>Scroll To Bottom </Button>
</ScrollView>
)
}
You can also do this using the useRef hook.
const scrollView = useRef();
const scrollView = useRef();
const onPress = () => {
scrollView.current.scrollToEnd();
}
<Button onPress={onPress} />
This question is quite similar to this one but isn't exactly the same, that is why i'll provide an answer.
ScrollView provide a ScrollTo() method that allows you to scroll to a x/y position in your scrollview.
let _scrollViewBottom
<ScrollView
ref='_scrollView'
onContentSizeChange={(contentWidth, contentHeight)=>{
_scrollViewBottom = contentHeight;
}}>
</ScrollView>
then use the ref name of the scroll view like
this.refs._scrollView.scrollTo(_scrollViewBottom);
Additionally, if your goal is to frequently push new data and scroll at the end of your scrollview, you might wanna take a look at react-native-invertible-scroll-view.
InvertibleScrollView is a React Native scroll view that can be inverted so that content is rendered starting from the bottom, and the user must scroll down to reveal more. This is a common design in chat applications
For functional component
<ScrollView
ref={ref => { scrollView = ref }}
onContentSizeChange={() => scrollView.scrollToEnd({ animated: true })}
>
...
</ScrollView>
For class component
<ScrollView
ref={ref => { this.scrollView = ref }}
onContentSizeCange={() => this.scrollView.scrollToEnd({ animated: true })}
>
...
</ScrollView>
let _scrollViewBottom
<ScrollView
ref={scrollViewRef}
onContentSizeChange={(contentWidth, contentHeight)=>{
_scrollViewBottom = contentHeight;
// this make move your scroll
scrollViewRef.current.scrollTo({x:0,y:_scrollViewBottom ,animated:true});
}}>
</ScrollView>
Additionally, if your goal is to frequently push new data and scroll at the end of your scrollview, you might wanna take a look at react-native-invertible-scroll-view.
InvertibleScrollView is a React Native scroll view that can be inverted so that content is rendered starting from the bottom, and the user must scroll down to reveal more. This is a common design in chat applications

React Native - Move Button on Tap

I'm new to React Native (experiences iOS developer in Swift) and I can't seem to find anything online for how to move UI elements in response to touch events. (Or maybe I'm just really bad at searching stack overflow lol).
Eventually, I want to have a textbox in the center of the screen, and when the user begins to type (or taps on the box to start typing), the box will slide to the top of the screen. However I can't even find a simple tutorial for this. I know that I can have a const style that defines style/position aspects of the textbox, and I can create a second style and then on button tap I can change the textbox's style and re-render, but it seems overkill to make an entire second style, where only one attribute is changing.
Can someone provide sample React Native code, where there is a text label and a button on the screen, and when the user taps the button, the label moves from above the button to below the button?
Check out this example of moving an element on touch. I use a <TouchableWithoutFeedback> and onPressIn. When you touch it, it changes the x and y position of it:
https://snack.expo.io/#noitsnack/onpressin-twice
import React, { Component } from 'react';
import { Text, View, TouchableWithoutFeedback, Image, Dimensions } from 'react-native';
import IMAGE_EXPO from './assets/expo.symbol.white.png'
const IMAGE_SIZE = 100;
export default class App extends Component {
state = {
score: 0,
...getRandXY()
}
render() {
const { score, x, y } = this.state;
return (
<View style={{flex:1, backgroundColor:'steelblue' }}>
<Text style={{fontSize:72, textAlign:'center'}}>{score}</Text>
<TouchableWithoutFeedback onPressIn={this.addScore}>
<Image source={IMAGE_EXPO} style={{ width:IMAGE_SIZE, height:IMAGE_SIZE, left:x, top:y, position:'absolute' }} />
</TouchableWithoutFeedback>
</View>
)
}
addScore = e => {
this.setState(({ score }) => ({ score:score+1, ...getRandXY() }));
}
}
function getRandXY() {
return {
x: getRandInt(0, Dimensions.get('window').width - IMAGE_SIZE),
y: getRandInt(0, Dimensions.get('window').height - IMAGE_SIZE)
}
}
function getRandInt(min, max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
Once you get this movement down you can move to the Animation API to get teh sliding effect.

Resources