I'm trying to have the image fill the bounds of the lime box.
It works when zoom === 1, positionDelta === [0,0]:
But behaving in a way that I don't expect when zoom === 0.688, positionDelta === [0,19]:
It should look like this (aside from the green stroke):
import computeFilters from './computeFilters';
import { useState } from 'react';
import imageMap from './imageMap';
export default function SvgImage({state,value,bounds,div, imageUrlMap}){
const [dataUrl, setDataUrl] = useState(null);
let {width, height, x, y} = bounds;
let cropId = value.value.cropId;
let crop = state.cropsById[ cropId ];
let imageId = crop.imageId || state.imageSets[crop.imageSetId].figureImageId;
let imageSet = state.imageSets[ crop.imageSetId ];
let angle = imageSet.rotation;
let imageRecord = state.imageUploadsById[ imageId ];
let url = imageRecord.url;
let adjustments = imageRecord.adjustments;
let imgStyle = {height:crop.height * width, width, }
let clipId = 'clip-'+div.id;
console.log(value);
let href = imageUrlMap[value._id]
let zoom = (value.imageAdjustments && value.imageAdjustments.zoom) || 1;
let [deltaX,deltaY] = (
value.imageAdjustments && value.imageAdjustments.positionDelta
) || [0,0];
let imageX = x + deltaX;
let imageY = y + deltaY;
let imageWidth = width * zoom;
let imageHeight = height * zoom;
console.log(JSON.stringify({imageX,imageY,imageWidth,imageHeight,zoom,deltaX,deltaY}))
return(
<>
<rect stroke="red" strokeWidth={1} x={x} y={y} width={width} height={height} fill={"none"}/>
<rect stroke="lime" strokeWidth={3}
x={imageX} y={imageY}
width={imageWidth} height={imageHeight} fill={"none"}/>
<image
xlinkHref={href}
width={imageWidth}
height={imageHeight}
x={imageX}
y={imageY}
preserveAspectRatio="none"
/>
</>
)
}
And if I set the following:
xlinkHref={href}
width={width}
height={height}
x={imageX}
y={imageY}
preserveAspectRatio="none"
/>
I get this:
I can try to clip it, but I don't understand why it won't just scale the way I tell it to and it feels the need to rudely insert more than I'm asking for into the view uninvited.
The console log for the three images are:
{"imageX":52,"imageY":95,"imageWidth":309.59999999999997,"imageHeight":87.37599999999999,"zoom":0.688,"deltaX":0,"deltaY":19}
{"imageX":52,"imageY":203,"imageWidth":450,"imageHeight":38,"zoom":1,"deltaX":0,"deltaY":0}
{"imageX":52,"imageY":241,"imageWidth":450,"imageHeight":51,"zoom":1,"deltaX":0,"deltaY":0}
Related
I have the next problem I'm trying to create a draggable world globe with d3 in a svelte app, the problem that i have is when a try to drag the globe the drag action is laggy I think that my problem have someting to do with a memory leak in the draggable component I don't know if this is the main reason of this laggy behaviour. The globe was drew with svg's
This is the App link:
https://codesandbox.io/s/cocky-benz-2mk5bs
Draggable component
<script>
import { onMount, onDestroy, afterUpdate } from 'svelte';
import { mouseAdjusted } from '../lib/Utilities';
onMount(() => console.log('mounted'));
afterUpdate(() => {
//console.log('Destroyed');
});
export let mouseX;
export let mouseY;
let offset;
let isMove = false;
const start = (e) => {
isMove = true;
const element = e.target;
const target = e.target.parentElement.parentElement.getScreenCTM();
// get the mouse position in the svg shape
offset = mouseAdjusted(e.clientX, e.clientY, target);
// rest the shape mouse posicion from the shape x y coordinates
offset[1] -= +element.getAttributeNS(null, 'y');
offset[0] -= +element.getAttributeNS(null, 'x');
};
const move = (e) => {
if (isMove) {
const target = e.target.parentElement.parentElement.getScreenCTM();
const [x, y] = mouseAdjusted(e.clientX, e.clientY, target);
mouseX = offset[0] - x;
mouseY = offset[1] - y;
}
};
const end = () => {
isMove = false;
offset = null;
};
</script>
<svelte:window
on:mousemove|preventDefault|stopPropagation={move}
on:mouseup|preventDefault|stopPropagation={end}
/>
<g class="draggable" on:mousedown|preventDefault|stopPropagation={start}>
<slot />
</g>
Graph component
<script>
import { onMount, onDestroy } from "svelte";
import * as d3 from "d3";
import * as topojson from "topojson-client";
import Draggable from "./draggable.svelte";
let width = 500;
$: width = width * 0.95;
let height = 500;
$: height = height * 0.98;
let world;
let x;
let y;
let projection;
let path;
let ROTATION = [-45, -65, 0];
// Add topojsom
onMount(async () => {
const resp = await d3.json(
"/src/assets/world-administrative-boundaries.json"
);
world = await topojson.feature(resp, "world-administrative-boundaries");
});
$: ROTATION = [-x, y, 0];
$: projection = d3
.geoOrthographic()
.fitSize([width, height], world)
.scale([width / 3])
.rotate(ROTATION);
$: path = d3.geoPath(projection);
const fillScale = d3
.scaleOrdinal()
.domain(["", ""])
.range([" hsl(40, 98%, 47%)", "hsl(9, 64%, 50%)"])
.unknown("hsl(227, 16%, 42%)");
const strokeScale = d3
.scaleOrdinal()
.domain(["", ""])
.range([" hsl(40, 98%, 35%)", "hsl(9, 64%, 35%)"])
.unknown("hsl(227, 16%, 22%)");
// transform to features
$: countries = world?.features.map(obj => {
const { geometry, properties, _ } = obj;
//const d = path(geometry);
const fill = fillScale(properties.iso3);
const stroke = strokeScale(properties.iso3);
const newProperties = Object.assign({ ...properties }, { fill, stroke });
return Object.assign({}, { geometry, properties: newProperties });
});
// $: console.log('features', features);
//$: console.log('first', ROTATION);
</script>
<svelte:window bind:innerWidth={width} bind:innerHeight={height} />
<svg {width} {height}>
<Draggable bind:mouseX={x} bind:mouseY={y}>
{#if countries}
<path class="sphere" d={path({ type: 'Sphere' })} />
<g class="countries">
{#each countries as country}
<path
d={path(country.geometry)}
fill={country.properties.fill}
stroke={country.properties.stroke}
/>
{/each}
</g>
{/if}
</Draggable>
</svg>
<!-- markup (zero or more items) goes here -->
<style>
svg {
border: 1px solid tomato;
}
.sphere {
fill: var(--base-color-2);
}
</style>
I create text on canvas using KonvaJS. And I can freeze the text using Transformer. While drawing, the origin remains in the center as I wish there is no problem here.
However, when I want to use the data with svg here, x andy come true without freezing. But when I do ice cream it freezes outside the center. Here
transform={{
rotation: 90,
originX: x + width / 2,
originY: y + height / 2,
}}
It works when I freeze using it. Because x and y values are not changing. However, while drawing on KonvJs, if I freeze, the values of xtation andy change together with the value of ratation.
The code between the shortened example.
import React, { Fragment, useEffect, useRef } from 'react'
import { Text, Transformer } from 'react-konva'
import { useStore } from './store'
export default function ({ id, text }) {
const { regions, selected, setRegions, setSelected } = useStore()
const { x, y, value, color, rotation, fontSize } = text
const TextRef = useRef()
const TransformRef = useRef()
const onDragEnd = ({ target }) => {
setRegions(
regions.map((item) => {
if (item.id === id) {
item.text = {
...item.text,
x: target.x(),
y: target.y(),
width: target.width(),
height: target.height(),
}
}
return item
})
)
}
const onTransformEnd = () => {
const node = TextRef.current
const width = node.width()
const height = node.height()
const x = node.x()
const y = node.y()
const rotation = node.rotation()
const originX = x + width / 1.3
const originY = y + height / 1.3
setRegions(
regions.map((item) => {
if (item.id === id) {
item.text = {
...item.text,
x, // <= it changes when this is rotation
y, // <= it changes when this is rotation
rotation,
originX,
originY,
}
}
return item
})
)
}
const isSelected = id === selected
useEffect(() => {
if (isSelected) {
TransformRef.current.setNode(TextRef.current)
TransformRef.current.getLayer().batchDraw()
}
}, [isSelected])
return (
<Fragment>
<Text
draggable
name="region"
x={x}
y={y}
text={value}
fill={color}
ref={TextRef}
rotation={rotation}
fontSize={fontSize}
onDragEnd={onDragEnd}
onTransformEnd={onTransformEnd}
/>
{isSelected && (
<Transformer
ref={TransformRef}
/>
)}
</Fragment>
)
}
It will be enough to work in the section I made by giving offset in the convention. The important example is that I can show with svg on the client side. React Native Svg
<G
transform={{
rotation: rotation,
originX: x + width / 2,
originY: y + height / 2,
}}>
<Text
x={x}
y={y}
fill={'#fff'}
fontSize={fontSize}
textAnchor="start"
>
{value}
</Text>
</G>
You may need to calculate the center of the shape, to position it in SVG correctly.
function getCenter(shape) {
return {
x:
shape.x +
(shape.width / 2) * Math.cos(shape.rotation) +
(shape.height / 2) * Math.sin(-shape.rotation),
y:
shape.y +
(shape.height / 2) * Math.cos(shape.rotation) +
(shape.width / 2) * Math.sin(shape.rotation)
};
}
function Show({ text, x, y, rotation, width, height }) {
const center = getCenter({
x,
y,
width,
height,
rotation: (rotation / 180) * Math.PI
});
return (
<svg width={window.innerWidth} height={window.innerHeight / 2}>
<text
y={height / 1.3}
fill="#000"
fontSize={50}
alignment-baseline="bottom"
transform={`translate(${x}, ${y}) rotate(${rotation})`}
>
{text}
</text>
{/* Origin Circl */}
<circle cx={center.x} cy={center.y} r={10} fill="red" />
</svg>
);
}
Demo: https://codesandbox.io/s/konva-and-svg-demo-jx7sj?file=/src/Playground.js:1704-2583
I'm writing a component (React) which draws a fancy box around a bit of text with SVG. The component receives the width and height of the dom element and draws a polygon derived from those values. Simplified example follows:
import React from 'react';
const Box = ({ dimensions }) => {
const { width, height } = dimensions;
const mod = 10;
const tlX = 0;
const tlY = 0;
const trX = tlX + width;
const trY = tlY;
const brX = trX;
const brY = trY + height;
const blX = 0;
const blY = tlY + height;
return (
<picture>
<svg height={height + 50} width={width + 200}>
<polygon
points={`${tlX},${tlY} ${trX},${trY} ${brX},${brY} ${blX},${blY}`}
style={{ fill: 'black', fillOpacity: '0.5' }}
/>
</svg>
</picture>
);
};
In this stripped down example the result is a rectangle with straight corners based on the width and height of the supplied dom element. In reality these values are given some random modifiers to create more of a trapezoid, as in fig A.
Illustration of desired result
In the fig B you can see my problem with this method. When drawing a longer or shorter box, the figure looks squished. What I want is for the box to behave like in fig C, in that it will draw the horizontal lines at a given angle until it has reached a certain width.
From what I can intuit this should be possible with some math savvy, but I am unable to quite figuring it out on my own.
Thanks in advance for any input, and please let me know if I'm being unclear on anything.
Edit:
A "trapezoid" shape is apparently not what I'm looking for. My apologies. I just want a sort of janky rectangle. I was asked to show the code I've been using in more detail. As you will see I am basically just taking the values from the last example and messing them up a bit by adding or subtracting semi-randomly.
import React from 'react';
import PropTypes from 'prop-types';
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
const point = (core, edge) => getRandomArbitrary(core - edge, core + edge);
const Box = ({ dimensions }) => {
const { width, height } = dimensions;
const mod = 10;
const tlX = point(25, mod);
const tlY = point(40, mod);
const trX = point(width + 55, mod);
const trY = point(25, mod);
const brX = point(width + 25, mod);
const brY = point(height - 25, mod);
const blX = point(5, mod);
const blY = point(height - 40, mod);
return (
<picture>
<svg height={height + 50} width={width + 200}>
<polygon
points={`${tlX},${tlY} ${trX},${trY} ${brX},${brY} ${blX},${blY}`}
style={{ fill: 'black', fillOpacity: '0.5' }}
/>
</svg>
</picture>
);
};
Box.propTypes = {
dimensions: PropTypes.shape({
width: PropTypes.number,
height: PropTypes.number,
}).isRequired,
};
export default Box;
In order to calculate the y for the top right point I'm imagining a circle with the center in the top left point. The radius of the circle is tlX - trX, The angle is -5 degs but you can change it to what you need. In order to calculate the value for the y you can do
const trY = tlY - (tlX - trX)*Math.sin(a1)
To calculate the y for the bottom right point I'm doing the same only this time the angle is 5 degs, the center in the bottom left point and the radius of the circle is blX - brX
const brY = blY - (blX - brX)*Math.sin(a2)
The important part of the demo is this:
//calculating the points for the polygon
const tlX = BB.x-10;
const tlY = BB.y-5;
const trX = tlX + 20 + BB.width;
//const trY = tlY - 10;
const trY = tlY - (tlX - trX)*Math.sin(a1)
const brX = trX - 5;
const blX = tlX + 5;
const blY = tlY + 10 + BB.height;
//const brY = trY + 30+ BB.height;
const brY = blY - (blX - brX)*Math.sin(a2)
Next comes a demo where I'm using plain javascript. Please change the length of the text to see if this is what you need.
let bb = txt.getBBox();
let m = 10;
// the blue rect
updateSVGelmt({x:bb.x-m,y:bb.y-m,width:bb.width+2*m,height:bb.height+2*m},theRect)
// the bounding box of the blue rect
let BB = theRect.getBBox();
//the angles for the polygon
let a1 = -5*Math.PI/180;
let a2 = -a1;
//calculating the points for the polygon
const tlX = BB.x-10;
const tlY = BB.y-5;
const trX = tlX + 20 + BB.width;
//const trY = tlY - 10;
const trY = tlY - (tlX - trX)*Math.sin(a1)
const brX = trX - 5;
const blX = tlX + 5;
const blY = tlY + 10 + BB.height;
//const brY = trY + 30+ BB.height;
const brY = blY - (blX - brX)*Math.sin(a2)
let points = `${tlX},${tlY} ${trX},${trY} ${brX},${brY} ${blX},${blY}`;
poly.setAttributeNS(null, "points", points)
let polybox = poly.getBBox();
svg.setAttributeNS(null, "viewBox", `${polybox.x-2} ${polybox.y-2} ${polybox.width+4} ${polybox.height+4}`)
svg.setAttributeNS(null, "width",3*(polybox.width+4))
function updateSVGelmt(o,elmt) {
for (let name in o) {
if (o.hasOwnProperty(name)) {
elmt.setAttributeNS(null, name, o[name]);
}
}
}
svg{border:1px solid}
<svg id="svg">
<polygon id="poly"
points=""
style="stroke: black; fill:none"
/>
<rect id="theRect" fill="#d9d9ff" />
<text id="txt" text-anchor="middle">element</text>
</svg>
I have an issue: I have to change element position&angle on scroll event. Like my webpage is a long road with background - and I need to animate car movements along this path during the scroll.
I good explanation is here: http://prinzhorn.github.io/skrollr-path/ - a perfect solution, that meets my requirements. But Unfortunately it's extremely outdated.
Maybe somebody has an up to date solution-library? Or code-ideas, how to animate element via svg-path with page scrolling?
Also i tried http://scrollmagic.io/examples/expert/bezier_path_animation.html - but it's not something that I need, because my path is difficult. Not just a couple of circles.
Here is some vanilla Javascript that moves a "car" along a path according to how much the page has scrolled.
It should work in all (most) browsers. The part that you may need to tweak is how we get the page height (document.documentElement.scrollHeight). You may need to use different methods depending on the browsers you want to support.
function positionCar()
{
var scrollY = window.scrollY || window.pageYOffset;
var maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
var path = document.getElementById("path1");
// Calculate distance along the path the car should be for the current scroll amount
var pathLen = path.getTotalLength();
var dist = pathLen * scrollY / maxScrollY;
var pos = path.getPointAtLength(dist);
// Calculate position a little ahead of the car (or behind if we are at the end), so we can calculate car angle
if (dist + 1 <= pathLen) {
var posAhead = path.getPointAtLength(dist + 1);
var angle = Math.atan2(posAhead.y - pos.y, posAhead.x - pos.x);
} else {
var posBehind = path.getPointAtLength(dist - 1);
var angle = Math.atan2(pos.y - posBehind.y, pos.x - posBehind.x);
}
// Position the car at "pos" totated by "angle"
var car = document.getElementById("car");
car.setAttribute("transform", "translate(" + pos.x + "," + pos.y + ") rotate(" + rad2deg(angle) + ")");
}
function rad2deg(rad) {
return 180 * rad / Math.PI;
}
// Reposition car whenever there is a scroll event
window.addEventListener("scroll", positionCar);
// Position the car initially
positionCar();
body {
min-height: 3000px;
}
svg {
position: fixed;
}
<svg width="500" height="500"
viewBox="0 0 672.474 933.78125">
<g transform="translate(-54.340447,-64.21875)" id="layer1">
<path d="m 60.609153,64.432994 c 0,0 -34.345187,72.730986 64.649767,101.015256 98.99494,28.28427 321.2285,-62.62946 321.2285,-62.62946 0,0 131.31984,-52.527932 181.82746,16.16244 50.50763,68.69037 82.04198,196.41856 44.44671,284.86302 -30.25843,71.18422 -74.75128,129.29952 -189.90867,133.34013 -115.15739,4.04061 -72.73099,-153.54318 -72.73099,-153.54318 0,0 42.42641,-129.29953 135.36044,-119.198 92.93404,10.10152 -14.14213,-129.29953 -141.42135,-94.95434 -127.27922,34.34518 -183.84777,80.8122 -206.07112,121.2183 -22.22336,40.40611 -42.06243,226.23742 -26.26397,305.06607 8.77013,43.75982 58.20627,196.1403 171.72594,270.72088 73.8225,48.50019 181.82745,2.02031 181.82745,2.02031 0,0 94.95434,-12.12183 78.7919,-155.56349 -16.16244,-143.44166 -111.68403,-138.77778 -139.9683,-138.77778 -28.28427,0 83.39976,-156.18677 83.39976,-156.18677 0,0 127.27922,-189.90867 107.07617,16.16245 C 634.3758,640.21994 864.69058,888.71747 591.94939,941.2454 319.2082,993.77334 -16.162441,539.20469 153.54319,997.81395"
id="path1"
style="fill:none;stroke:#ff0000;stroke-width:4;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"/>
<path id="car" d="M-15,-10 L15,0 L -15,10 z" fill="yellow" stroke="red" stroke-width="7.06"/>
</g>
</svg>
I adapted Paul LeBau's answer for my purposes in TypeScript and figured I'd leave it here in case it's helpful for anyone.
NOTE: It's broken as hell when running the snippet in Stack Overflow. No clue why when it functions perfectly in VSCode. First thing I'd recommended is full screening the snippet if you can't see the SVG. Then actually try copy/pasting this into your own project before making any claims about there being an issue with the posted code.
Notable additions from Paul's:
A clickToScroll function allowing you to click anywhere on the svg path and have it scroll accordingly (does not work at all in the SO snippet window)
The car (rider) will face towards the direction it's moving
Here's the Typescript version separately as SO doesn't support TS :(
interface PathRider {
ride: () => void;
clickToScroll: (e: MouseEvent) => void;
onClick: (e: MouseEvent, callback: (pt: DOMPoint) => void) => void;
};
const usePathRider = (
rider: SVGPathElement,
path: SVGPathElement,
rideOnInit = true
): PathRider => {
const maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
const pathLen = path.getTotalLength();
//====================
/* Helper Functions */
const radToDeg = (rad: number) => (180 * rad) / Math.PI;
const distance = (a: DOMPoint, b: DOMPoint) =>
Math.sqrt(Math.pow(a.y - b.y, 2) + Math.pow(a.x - b.x, 2));
//=========================
/* Click-based Functions */
const step = 0.5; // how granularly it should check for the point on the path closest to where the user clicks. the lower the value the less performant the operation is
let currLen = -step;
const pointArr: DOMPoint[] = [];
while ((currLen += step) <= pathLen)
pointArr.push(path.getPointAtLength(currLen));
const onClick = (e: MouseEvent, callback: (pt: DOMPoint) => void) => {
let pt = new DOMPoint(e.clientX, e.clientY);
callback(pt.matrixTransform(path.getScreenCTM().inverse()));
};
const getLengthAtPoint = (pt: DOMPoint) => {
let bestGuessIdx = 0;
let bestGuessDist = Number.MAX_VALUE;
let guessDist: number;
pointArr.forEach((point, idx) => {
if ((guessDist = distance(pt, point)) < bestGuessDist) {
bestGuessDist = guessDist;
bestGuessIdx = idx;
}
});
return bestGuessIdx * step;
};
const getScrollPosFromLength = (len: number) => (len * maxScrollY) / pathLen;
const clickToScroll = (e: MouseEvent) => {
onClick(e, (point) => {
const lengthAtPoint = getLengthAtPoint(point);
const scrollPos = getScrollPosFromLength(lengthAtPoint);
window.scrollTo({
top: scrollPos,
behavior: 'smooth',
});
});
};
//==========================
/* Scroll-based functions */
let lastDist: number; // for determining direction
const ride = () => {
const scrollY = window.scrollY || window.pageYOffset;
const dist = (pathLen * scrollY) / maxScrollY;
const pos = path.getPointAtLength(dist);
let angle: number;
// calculate position a little ahead of the rider (or behind if we are at the end),
// so we can calculate the rider angle
const dir = lastDist < dist; // true=right
if (dir ? dist + 1 <= pathLen : dist - 1 >= 0) {
const nextPos = path.getPointAtLength(dist + (dir ? 1 : -1));
angle = Math.atan2(nextPos.y - pos.y, nextPos.x - pos.x);
} else {
const nextPos = path.getPointAtLength(dist + (dir ? -1 : 1));
angle = Math.atan2(pos.y - nextPos.y, pos.x - nextPos.x);
}
lastDist = dist;
rider.setAttribute(
'transform',
`translate(${pos.x}, ${pos.y}) rotate(${radToDeg(angle)})`
);
};
if (rideOnInit) ride();
return {
ride,
clickToScroll,
onClick,
};
};
Snippets for running in SO
const usePathRider = (
rider,
path,
rideOnInit = true
) => {
const maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
const pathLen = path.getTotalLength();
const step = 0.5;
let currLen = -step;
const pointArr = [];
while ((currLen += step) <= pathLen)
pointArr.push(path.getPointAtLength(currLen));
//====================
/* Helper Functions */
const radToDeg = (rad) => (180 * rad) / Math.PI;
const distance = (a, b) =>
Math.sqrt(Math.pow(a.y - b.y, 2) + Math.pow(a.x - b.x, 2));
//============
/* Closures */
const onClick = (e, callback) => {
let pt = new DOMPoint(e.clientX, e.clientY);
callback(pt.matrixTransform(path.getScreenCTM().inverse()));
};
const getLengthAtPoint = (pt) => {
let bestGuessIdx = 0;
let bestGuessDist = Number.MAX_VALUE;
let guessDist;
pointArr.forEach((point, idx) => {
if ((guessDist = distance(pt, point)) < bestGuessDist) {
bestGuessDist = guessDist;
bestGuessIdx = idx;
}
});
return bestGuessIdx * step;
};
const getScrollPosFromLength = (len) => (len * maxScrollY) / pathLen;
const clickToScroll = (e) => {
onClick(e, (point) => {
const lengthAtPoint = getLengthAtPoint(point);
const scrollPos = getScrollPosFromLength(lengthAtPoint);
window.scrollTo({
top: scrollPos,
behavior: 'smooth',
});
});
};
let lastDist;
const ride = () => {
const scrollY = window.scrollY || window.pageYOffset;
const dist = (pathLen * scrollY) / maxScrollY;
const pos = path.getPointAtLength(dist);
let angle;
// calculate position a little ahead of the rider (or behind if we are at the end),
// so we can calculate the rider angle
const dir = lastDist < dist; // true=right
if (dir ? dist + 1 <= pathLen : dist - 1 >= 0) {
const nextPos = path.getPointAtLength(dist + (dir ? 1 : -1));
angle = Math.atan2(nextPos.y - pos.y, nextPos.x - pos.x);
} else {
const nextPos = path.getPointAtLength(dist + (dir ? -1 : 1));
angle = Math.atan2(pos.y - nextPos.y, pos.x - nextPos.x);
}
lastDist = dist;
rider.setAttribute(
'transform',
`translate(${pos.x}, ${pos.y}) rotate(${radToDeg(angle)})`
);
};
if (rideOnInit) ride();
return {
ride,
clickToScroll,
onClick,
};
};
/* VANILLA JS USAGE */
const svgRider = document.getElementById('rider');
const svgPath = document.getElementById('path');
const pathRider = usePathRider(svgRider, svgPath);
// Reposition car whenever there is a scroll event
window.addEventListener("scroll", pathRider.ride);
body {
min-height: 3000px;
}
svg {
position: fixed;
}
<svg onclick="pathRider.clickToScroll" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 285" shape-rendering="geometricPrecision" text-rendering="geometricPrecision"><path
id="path"
d="M22.061031,163.581791c.750375-2.251126,2.251125-16.508254,26.263131-20.26013s20.26013-8.254128,42.02101,2.251125q21.76088,10.505253-12.006004,18.009005-33.016508.750374,0-18.009005t52.526263,4.427213q6.003001,19.584792,19.134567,14.332166t16.133067-14.332166q32.266133-12.081041,45.772886,0t47.273637,0"
transform="translate(.000002 0.000001)"
fill="none"
stroke="#3f5787"
stroke-width="0.6"
stroke-dasharray="3"
/>
<path
id="rider"
d="M-2,-2 L3,0 L -2,2 z"
stroke="red"
stroke-width="0.6"
/></svg
>
this is my function where am calculating image's height and width, but I had to use react native's image. getSizebut this has a callback which a has a delay somehow and the return brock seems to execute before this image. getSize finish.
renderNode (node, index, siblings, parent, defaultRenderer) {
let finalwidth ;
let finalheight;
if (node.name === 'img') {
const a = node.attribs;
Image.getSize(a.src, (width, height) => {
let screenSize = Dimensions.get('window');
let hRatio = screenSize.width / width;
let vRatio = screenSize.height / height;
let ratio = Math.max(hRatio, vRatio);
let rat = hRatio / vRatio;
finalwidth = parseInt(width * ratio);
finalheight = parseInt(height * ratio);
alert(finalwidth + 'x' + finalheight) // they have values here
})
return (
<Image
key={index}
source={{uri: a.src}}
resizeMode={'stretch'}
style={{
width: finalwidth, //finalwidth is null here
height:finalheight, //finalheight is null here
}}
/>
);
}
}
Actually, I want to access the value of final width and final height in my return brock
use setState() and set those values into state so that the component is rerendered when the data is updated
constructor(props){
super(props);
this.state={finalwidth : null,
finalheight: null
}
}
renderNode (node, index, siblings, parent, defaultRenderer) {
if (node.name === 'img') {
const a = node.attribs;
Image.getSize(a.src, (width, height) => {
let screenSize = Dimensions.get('window');
let hRatio = screenSize.width / width;
let vRatio = screenSize.height / height;
let ratio = Math.max(hRatio, vRatio);
let rat = hRatio / vRatio;
finalwidth = parseInt(width * ratio);
finalheight = parseInt(height * ratio);
this.setState({finalwidth, finalheight})
alert(finalwidth + 'x' + finalheight) // they have values here
})
return (
<Image
key={index}
source={{uri: a.src}}
resizeMode={'stretch'}
style={{
width: this.state.finalwidth, //finalwidth from state
height: this.state.finalheight, //finalheight from state
}}
/>
);
}
}