scaling stickers

This commit is contained in:
Fedor Katurov 2020-02-11 15:10:43 +07:00
parent 09ce310bad
commit ef5cd0cdef
13 changed files with 181 additions and 144 deletions

View file

@ -1,4 +1,4 @@
import React from 'react'; import React, { memo } from 'react';
import { MainMap } from '~/constants/map'; import { MainMap } from '~/constants/map';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
@ -18,7 +18,6 @@ import 'leaflet/dist/leaflet.css';
import { selectEditorEditing, selectEditorMode, selectEditorGpx } from '~/redux/editor/selectors'; import { selectEditorEditing, selectEditorMode, selectEditorGpx } from '~/redux/editor/selectors';
import { MODES } from '~/constants/modes'; import { MODES } from '~/constants/modes';
import { selectUserLocation } from '~/redux/user/selectors'; import { selectUserLocation } from '~/redux/user/selectors';
import { GPX_ROUTE_COLORS } from '~/redux/editor/constants';
const mapStateToProps = state => ({ const mapStateToProps = state => ({
provider: selectMapProvider(state), provider: selectMapProvider(state),
@ -41,7 +40,8 @@ type IProps = React.HTMLAttributes<HTMLDivElement> &
ReturnType<typeof mapStateToProps> & ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps & {}; typeof mapDispatchToProps & {};
const MapUnconnected: React.FC<IProps> = ({ const MapUnconnected: React.FC<IProps> = memo(
({
provider, provider,
stickers, stickers,
editing, editing,
@ -90,18 +90,13 @@ const MapUnconnected: React.FC<IProps> = ({
{gpx.enabled && {gpx.enabled &&
gpx.list.map( gpx.list.map(
({ latlngs, enabled, color }, index) => ({ latlngs, enabled, color }, index) =>
enabled && ( enabled && <GpxPolyline latlngs={latlngs} color={color} key={index} />
<GpxPolyline
latlngs={latlngs}
color={color}
key={index}
/>
)
)} )}
</div>, </div>,
document.getElementById('canvas') document.getElementById('canvas')
); );
}; }
);
const Map = connect(mapStateToProps, mapDispatchToProps)(MapUnconnected); const Map = connect(mapStateToProps, mapDispatchToProps)(MapUnconnected);
export { Map }; export { Map };

View file

@ -13,6 +13,7 @@ interface IProps {
onDragStart?: () => void; onDragStart?: () => void;
index: number; index: number;
is_editing: boolean; is_editing: boolean;
zoom: number;
mapSetSticker: (index: number, sticker: IStickerDump) => void; mapSetSticker: (index: number, sticker: IStickerDump) => void;
mapDropSticker: (index: number) => void; mapDropSticker: (index: number) => void;
@ -29,13 +30,16 @@ const getX = e =>
const Sticker: React.FC<IProps> = ({ const Sticker: React.FC<IProps> = ({
sticker, sticker,
index, index,
is_editing,
zoom,
mapSetSticker, mapSetSticker,
mapDropSticker, mapDropSticker,
is_editing,
}) => { }) => {
const [text, setText] = useState(sticker.text); const [text, setText] = useState(sticker.text);
const [layer, setLayer] = React.useState<Marker>(null); const [layer, setLayer] = React.useState<Marker>(null);
const [dragging, setDragging] = React.useState(false); const [dragging, setDragging] = React.useState(false);
const wrapper = useRef(null);
let angle = useRef(sticker.angle); let angle = useRef(sticker.angle);
const element = React.useMemo(() => document.createElement('div'), []); const element = React.useMemo(() => document.createElement('div'), []);
@ -146,6 +150,14 @@ const Sticker: React.FC<IProps> = ({
setText(sticker.text); setText(sticker.text);
}, [layer, sticker.text]); }, [layer, sticker.text]);
useEffect(() => {
if (!wrapper || !wrapper.current) return;
const scale = zoom / 13;
wrapper.current.style.transform = `scale(${scale}) perspective(1px)`
}, [zoom, wrapper]);
// Attaches onMoveFinished event to item // Attaches onMoveFinished event to item
React.useEffect(() => { React.useEffect(() => {
if (!layer) return; if (!layer) return;
@ -200,8 +212,9 @@ const Sticker: React.FC<IProps> = ({
element.className = is_editing ? 'sticker-container' : 'sticker-container inactive'; element.className = is_editing ? 'sticker-container' : 'sticker-container inactive';
}, [element, is_editing, layer]); }, [element, is_editing, layer]);
return createPortal( return createPortal(
<React.Fragment> <div ref={wrapper} className="sticker-wrapper">
<div className="sticker-arrow" ref={stickerArrow} /> <div className="sticker-arrow" ref={stickerArrow} />
<div className={classNames(`sticker-label ${direction}`)} ref={stickerImage}> <div className={classNames(`sticker-label ${direction}`)} ref={stickerImage}>
<StickerDesc value={text} onChange={onTextChange} onBlur={onTextBlur} /> <StickerDesc value={text} onChange={onTextChange} onBlur={onTextBlur} />
@ -220,7 +233,7 @@ const Sticker: React.FC<IProps> = ({
<div className="sticker-delete" onMouseDown={onDelete} onTouchStart={onDelete} /> <div className="sticker-delete" onMouseDown={onDelete} onTouchStart={onDelete} />
</div> </div>
</React.Fragment>, </div>,
element element
); );
}; };

View file

@ -1,6 +1,6 @@
import React from 'react'; import React, { useState, memo, FC, useEffect, useCallback } from 'react';
import { IStickerDump } from '~/redux/map/types'; import { IStickerDump } from '~/redux/map/types';
import { FeatureGroup, Map } from 'leaflet'; import { FeatureGroup, Map, LeafletEvent } from 'leaflet';
import { Sticker } from '~/map/Sticker'; import { Sticker } from '~/map/Sticker';
import { mapSetSticker, mapDropSticker } from '~/redux/map/actions'; import { mapSetSticker, mapDropSticker } from '~/redux/map/actions';
import { MainMap } from '~/constants/map'; import { MainMap } from '~/constants/map';
@ -8,22 +8,34 @@ import { MainMap } from '~/constants/map';
interface IProps { interface IProps {
stickers: IStickerDump[]; stickers: IStickerDump[];
is_editing: boolean; is_editing: boolean;
mapSetSticker: typeof mapSetSticker; mapSetSticker: typeof mapSetSticker;
mapDropSticker: typeof mapDropSticker; mapDropSticker: typeof mapDropSticker;
} }
const Stickers: React.FC<IProps> = React.memo( const Stickers: FC<IProps> = memo(({ stickers, is_editing, mapSetSticker, mapDropSticker }) => {
({ stickers, is_editing, mapSetSticker, mapDropSticker }) => { const [layer, setLayer] = useState<FeatureGroup>(null);
const [layer, setLayer] = React.useState<FeatureGroup>(null); const [zoom, setZoom] = useState(16);
React.useEffect(() => { const onZoomChange = useCallback(
(event: LeafletEvent) => {
setZoom(event.target._zoom);
},
[setZoom]
);
useEffect(() => {
if (!MainMap) return; if (!MainMap) return;
const item = new FeatureGroup().addTo(MainMap.stickerLayer); const item = new FeatureGroup().addTo(MainMap.stickerLayer);
setLayer(item); setLayer(item);
MainMap.on('zoomend', onZoomChange);
return () => MainMap.stickerLayer.removeLayer(item); return () => {
}, [MainMap]); MainMap.off('zoomend', onZoomChange);
MainMap.stickerLayer.removeLayer(item);
};
}, [MainMap, onZoomChange]);
return ( return (
<div> <div>
@ -34,13 +46,13 @@ const Stickers: React.FC<IProps> = React.memo(
key={`${sticker.set}.${sticker.sticker}.${index}`} key={`${sticker.set}.${sticker.sticker}.${index}`}
index={index} index={index}
is_editing={is_editing} is_editing={is_editing}
zoom={zoom}
mapSetSticker={mapSetSticker} mapSetSticker={mapSetSticker}
mapDropSticker={mapDropSticker} mapDropSticker={mapDropSticker}
/> />
))} ))}
</div> </div>
); );
} });
);
export { Stickers }; export { Stickers };

View file

@ -139,23 +139,9 @@ function* getRenderData() {
yield composeImages({ geometry, images, ctx }); yield composeImages({ geometry, images, ctx });
yield composePoly({ points, ctx }); yield composePoly({ points, ctx });
// TODO: make additional dashed lines
// gpx.list.forEach(item => {
// if (!gpx.enabled || !item.enabled || !item.latlngs.length) return;
// composePoly({
// points: getPolyPlacement(item.latlngs),
// ctx,
// color: item.color,
// opacity: 0.5,
// weight: 9,
// dash: [12, 12],
// });
// });
yield composeArrows({ points, ctx }); yield composeArrows({ points, ctx });
yield composeDistMark({ ctx, points, distance }); yield composeDistMark({ ctx, points, distance });
yield composeStickers({ stickers: sticker_points, ctx }); yield composeStickers({ stickers: sticker_points, ctx, zoom: MainMap.getZoom() / 13 });
yield put(editorSetRenderer({ info: 'Готово', progress: 1 })); yield put(editorSetRenderer({ info: 'Готово', progress: 1 }));

View file

@ -79,3 +79,8 @@ export const mapSetAddressOrigin = (address_origin: IMapReducer['address_origin'
type: MAP_ACTIONS.SET_ADDRESS_ORIGIN, type: MAP_ACTIONS.SET_ADDRESS_ORIGIN,
address_origin, address_origin,
}); });
export const mapZoomChange = (zoom: number) => ({
type: MAP_ACTIONS.ZOOM_CHANGE,
zoom,
});

View file

@ -17,5 +17,6 @@ export const MAP_ACTIONS = {
SET_STICKERS: `${P}-SET_STICKERS`, SET_STICKERS: `${P}-SET_STICKERS`,
DROP_STICKER: `${P}-DROP_STICKER`, DROP_STICKER: `${P}-DROP_STICKER`,
MAP_CLICKED: `${P}-MAP_CLICKED` MAP_CLICKED: `${P}-MAP_CLICKED`,
ZOOM_CHANGE: `${P}-ZOOM_CHANGE`
} }

View file

@ -14,6 +14,7 @@ import {
mapSetLogo, mapSetLogo,
mapSetAddressOrigin, mapSetAddressOrigin,
mapSetStickers, mapSetStickers,
mapZoomChange,
} from './actions'; } from './actions';
const setMap = (state: IMapReducer, { map }: ReturnType<typeof mapSet>): IMapReducer => ({ const setMap = (state: IMapReducer, { map }: ReturnType<typeof mapSet>): IMapReducer => ({
@ -101,6 +102,11 @@ const setAddressOrigin = (state, { address_origin }: ReturnType<typeof mapSetAdd
address_origin address_origin
}); });
const zoomChange = (state, { zoom }: ReturnType<typeof mapZoomChange>): IMapReducer => ({
...state,
zoom
});
export const MAP_HANDLERS = { export const MAP_HANDLERS = {
[MAP_ACTIONS.SET_MAP]: setMap, [MAP_ACTIONS.SET_MAP]: setMap,
[MAP_ACTIONS.SET_PROVIDER]: setProvider, [MAP_ACTIONS.SET_PROVIDER]: setProvider,
@ -116,4 +122,5 @@ export const MAP_HANDLERS = {
[MAP_ACTIONS.SET_PUBLIC]: setPublic, [MAP_ACTIONS.SET_PUBLIC]: setPublic,
[MAP_ACTIONS.SET_LOGO]: setLogo, [MAP_ACTIONS.SET_LOGO]: setLogo,
[MAP_ACTIONS.SET_ADDRESS_ORIGIN]: setAddressOrigin, [MAP_ACTIONS.SET_ADDRESS_ORIGIN]: setAddressOrigin,
[MAP_ACTIONS.ZOOM_CHANGE]: zoomChange,
}; };

View file

@ -16,6 +16,7 @@ export interface IMapReducer {
description: string; description: string;
owner: { id: string }; owner: { id: string };
is_public: boolean; is_public: boolean;
zoom: number;
} }
export const MAP_INITIAL_STATE: IMapReducer = { export const MAP_INITIAL_STATE: IMapReducer = {
@ -29,6 +30,7 @@ export const MAP_INITIAL_STATE: IMapReducer = {
description: '', description: '',
owner: { id: null }, owner: { id: null },
is_public: false, is_public: false,
zoom: 13,
} }
export const map = createReducer(MAP_INITIAL_STATE, MAP_HANDLERS) export const map = createReducer(MAP_INITIAL_STATE, MAP_HANDLERS)

View file

@ -328,6 +328,10 @@ function* setChanged() {
yield put(editorSetChanged(true)); yield put(editorSetChanged(true));
} }
function* onZoomChange() {
}
export function* mapSaga() { export function* mapSaga() {
yield takeEvery( yield takeEvery(
[MAP_ACTIONS.SET_ROUTE, MAP_ACTIONS.SET_STICKER, MAP_ACTIONS.SET_STICKERS], [MAP_ACTIONS.SET_ROUTE, MAP_ACTIONS.SET_STICKER, MAP_ACTIONS.SET_STICKERS],

View file

@ -7,3 +7,4 @@ export const selectMapRoute= (state: IState) => state.map.route;
export const selectMapStickers = (state: IState) => state.map.stickers; export const selectMapStickers = (state: IState) => state.map.stickers;
export const selectMapTitle= (state: IState) => state.map.title; export const selectMapTitle= (state: IState) => state.map.title;
export const selectMapAddress = (state: IState) => state.map.address; export const selectMapAddress = (state: IState) => state.map.address;
export const selectMapZoom = (state: IState) => state.map.zoom;

View file

@ -19,6 +19,8 @@ import { mapSaga } from '~/redux/map/sagas';
import { watchLocation, getLocation } from '~/utils/window'; import { watchLocation, getLocation } from '~/utils/window';
import { LatLngLiteral } from 'leaflet'; import { LatLngLiteral } from 'leaflet';
import { setUserLocation } from './user/actions'; import { setUserLocation } from './user/actions';
import { MainMap } from '~/constants/map';
import { mapZoomChange } from './map/actions';
const userPersistConfig: PersistConfig = { const userPersistConfig: PersistConfig = {
key: 'user', key: 'user',
@ -73,3 +75,4 @@ history.listen((location, action) => {
}); });
watchLocation((location: LatLngLiteral) => store.dispatch(setUserLocation(location))); watchLocation((location: LatLngLiteral) => store.dispatch(setUserLocation(location)));
MainMap.on('zoomend', event => store.dispatch(mapZoomChange(event.target._zoom)))

View file

@ -109,6 +109,11 @@
} }
} }
.sticker-wrapper {
will-change: transform;
transition: transform 50ms;
}
.sticker-arrow { .sticker-arrow {
position: absolute; position: absolute;
transform-origin: 0 0; transform-origin: 0 0;

View file

@ -103,9 +103,7 @@ export const getTilePlacement = (): ITilePlacement => {
}; };
export const getPolyPlacement = (latlngs: LatLng[]): Point[] => export const getPolyPlacement = (latlngs: LatLng[]): Point[] =>
latlngs.length === 0 latlngs.length === 0 ? [] : latlngs.map(latlng => MainMap.latLngToContainerPoint(latlng));
? []
: latlngs.map(latlng => (MainMap.latLngToContainerPoint(latlng)));
export const getStickersPlacement = (stickers: IStickerDump[]): IStickerPlacement[] => export const getStickersPlacement = (stickers: IStickerDump[]): IStickerPlacement[] =>
stickers.length === 0 stickers.length === 0
@ -132,7 +130,7 @@ export const imageFetcher = (source: string): Promise<HTMLImageElement> =>
export const fetchImages = ( export const fetchImages = (
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
geometry: ITilePlacement, geometry: ITilePlacement,
provider, provider
): Promise<{ x: number; y: number; image: HTMLImageElement }[]> => { ): Promise<{ x: number; y: number; image: HTMLImageElement }[]> => {
const { minX, maxX, minY, maxY, zoom } = geometry; const { minX, maxX, minY, maxY, zoom } = geometry;
@ -144,7 +142,11 @@ export const fetchImages = (
} }
return Promise.all( return Promise.all(
images.map(({ x, y, source }) => imageFetcher(source).then(image => ({ x, y, image }))) images.map(({ x, y, source }) =>
imageFetcher(source)
.then(image => ({ x, y, image }))
.catch()
)
); );
}; };
@ -206,7 +208,6 @@ export const composePoly = ({
} }
if (color === 'gradient') { if (color === 'gradient') {
const gradient = ctx.createLinearGradient(minX, minY, minX, maxY); const gradient = ctx.createLinearGradient(minX, minY, minX, maxY);
gradient.addColorStop(0, COLORS.PATH_COLOR[0]); gradient.addColorStop(0, COLORS.PATH_COLOR[0]);
gradient.addColorStop(1, COLORS.PATH_COLOR[1]); gradient.addColorStop(1, COLORS.PATH_COLOR[1]);
@ -292,10 +293,12 @@ const composeStickerArrow = (
ctx: CanvasRenderingContext2D, ctx: CanvasRenderingContext2D,
x: number, x: number,
y: number, y: number,
angle: number angle: number,
scale: number
) => { ) => {
ctx.save(); ctx.save();
ctx.translate(x, y); ctx.translate(x, y);
ctx.scale(scale, scale);
ctx.rotate(angle + Math.PI * 0.75); ctx.rotate(angle + Math.PI * 0.75);
ctx.translate(-x, -y); ctx.translate(-x, -y);
ctx.fillStyle = '#ff3344'; ctx.fillStyle = '#ff3344';
@ -309,12 +312,12 @@ const composeStickerArrow = (
ctx.restore(); ctx.restore();
}; };
const measureRect = (x: number, y: number, width: number, height: number, reversed: boolean) => ({ const measureRect = (x: number, y: number, width: number, height: number, scale: number, reversed: boolean) => ({
rectX: reversed ? x - width - 36 - 10 : x, rectX: reversed ? x - width - 36 * scale - 10 * scale : x,
rectY: y - 7 - height / 2, rectY: y - 7 * scale - height / 2,
rectW: width + 36 + 10, rectW: width + 46 * scale,
rectH: height + 20, rectH: height + 20 * scale,
textX: reversed ? x - width - 36 : x + 36, textX: reversed ? x - width - 36 : x + 36 * scale,
}); });
const measureDistRect = ( const measureDistRect = (
@ -374,39 +377,32 @@ const composeStickerText = (
x: number, x: number,
y: number, y: number,
angle: number, angle: number,
text: string text: string,
scale: number
): void => { ): void => {
const rad = 56; const rad = 56;
const tX = Math.cos(angle + Math.PI) * rad - 30 + x + 28; const tX = (Math.cos(angle + Math.PI) * rad - 30 + 28) * scale + x;
const tY = Math.sin(angle + Math.PI) * rad - 30 + y + 29; const tY = (Math.sin(angle + Math.PI) * rad - 30 + 29) * scale + y;
ctx.font = '12px "Helvetica Neue", Arial'; ctx.font = `${12 * scale}px "Helvetica Neue", Arial`;
const lines = text.split('\n'); const lines = text.split('\n');
const { width, height } = measureText(ctx, text, 16); const { width, height } = measureText(ctx, text, 16 * scale);
const { rectX, rectY, rectW, rectH, textX } = measureRect( const { rectX, rectY, rectW, rectH, textX } = measureRect(
tX, tX,
tY, tY,
width, width,
height, height,
scale,
angle > -(Math.PI / 2) && angle < Math.PI / 2 angle > -(Math.PI / 2) && angle < Math.PI / 2
); );
// rectangle
// ctx.fillStyle = '#222222';
// ctx.beginPath();
// ctx.rect(
// rectX,
// rectY,
// rectW,
// rectH,
// );
// ctx.closePath();
// ctx.fill();
roundedRect(ctx, rectX, rectY, rectW, rectH, '#222222', 2); roundedRect(ctx, rectX, rectY, rectW, rectH, '#222222', 2);
// text // text
ctx.fillStyle = 'white'; ctx.fillStyle = 'white';
lines.map((line, i) => ctx.fillText(line, textX, rectY + 6 + 16 * (i + 1))); lines.map((line, i) => ctx.fillText(line, textX, rectY + (6 + 16 * (i + 1)) * scale));
// ctx.scale(1/scale, 1/scale);
}; };
export const composeDistMark = ({ export const composeDistMark = ({
@ -451,36 +447,43 @@ const composeStickerImage = async (
y: number, y: number,
angle: number, angle: number,
set: string, set: string,
sticker: string sticker: string,
scale: number
): Promise<void> => { ): Promise<void> => {
console.log({ scale });
const rad = 56; const rad = 56;
const tX = Math.cos(angle + Math.PI) * rad - 30 + (x - 8); const tX = (Math.cos(angle + Math.PI) * rad - 30 - 6) * scale + x;
const tY = Math.sin(angle + Math.PI) * rad - 30 + (y - 4); const tY = (Math.sin(angle + Math.PI) * rad - 30 - 6) * scale + y;
const offsetX = STICKERS[set].layers[sticker].off * 72; const offsetX = STICKERS[set].layers[sticker].off * 72;
return imageFetcher(STICKERS[set].url).then(image => await imageFetcher(STICKERS[set].url).then(image => {
ctx.drawImage(image, offsetX, 0, 72, 72, tX, tY, 72, 72) ctx.drawImage(image, offsetX, 0, 72, 72, tX, tY, 72 * scale, 72 * scale);
); });
return;
}; };
export const composeStickers = async ({ export const composeStickers = async ({
stickers, stickers,
ctx, ctx,
zoom,
}: { }: {
stickers: IStickerPlacement[]; stickers: IStickerPlacement[];
ctx: CanvasRenderingContext2D; ctx: CanvasRenderingContext2D;
zoom: number;
}): Promise<void> => { }): Promise<void> => {
if (!stickers || stickers.length < 0) return; if (!stickers || stickers.length < 0) return;
stickers.map(({ x, y, angle, text }) => { stickers.map(({ x, y, angle, text }) => {
composeStickerArrow(ctx, x, y, angle); composeStickerArrow(ctx, x, y, angle, zoom);
if (text) composeStickerText(ctx, x, y, angle, text); if (text) composeStickerText(ctx, x, y, angle, text, zoom);
}); });
await Promise.all( await Promise.all(
stickers.map(({ x, y, angle, set, sticker }) => stickers.map(({ x, y, angle, set, sticker }) =>
composeStickerImage(ctx, x, y, angle, set, sticker) composeStickerImage(ctx, x, y, angle, set, sticker, zoom)
) )
); );
}; };