How do I draw a line to point derived from angle? - javascript

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>

Related

Rotate a polygon in here maps api

I am making a navigation program around a building, i am trying to rotate the polygons around the top right point as the origin. I have tried multiple equations, but nothing seems to work.
this is the code to display the polygons, i have commented out the code that rotates the polygons.
const scaleX = 0.000000114939702;
const scaleY = 0.000000152939702;
const originX = 53.4724642;
const originY = -2.2393615;
//usage:
readTextFile("result.json", function(text){
const data = JSON.parse(text);
for (const i in data) {
const list = [];
list.push(data[i].C1, data[i].C2, data[i].C3, data[i].C4);
for (const j in list) {
list[j][0] = (originX-list[j][0]*scaleX)
list[j][1] = (-(list[j][1]*scaleY)+originY)
}
var width = list[0][0] - list[1][0];
var height = list[0][1] - list[3][1];
var distanceToOriginX = originX-list[0][0]
var distanceToOriginY = originY-list[0][1]
//list[0][0] = originX - Math.sin(0.524)*distanceToOriginX+height
//list[0][1] = originY + Math.cos(0.524)*distanceToOriginY+width
addPolygonToMap(map, (list[0][0]), (list[0][1]), (list[1][0]), (list[1][1]), (list[2][0]), (list[2][1]), (list[3][0]), (list[3][1]), 'rgba(0, 0, 255, 1)')
}
}); ```
This is my solution, i had to re-calculate the scale and the calculations had to be done before the co-ordinates were converted into longitude and latitude.
const scaleX = 0.000000107;
const scaleY = 0.000000171;
const originX = 53.4724642;
const originY = -2.2393615;
function readFile(filename, floor, colour) {
readTextFile(filename, function(text){
const data = JSON.parse(text);
for (const i in data) {
const list = [];
list.push(data[i].C1, data[i].C2, data[i].C3, data[i].C4);
var angle = 0.484
for (const j in list) {
var distanceToOrigin = pythagorean(list[j][1], list[j][0])
var ang = 1.5708-(angle + Math.atan(list[j][0]/list[j][1]))
list[j][0] = originX-(Math.cos(ang)*distanceToOrigin)*scaleX
list[j][1] = originY-(Math.sin(ang)*distanceToOrigin)*scaleY
}
addPolygonToMap(map, (list[0][0]), (list[0][1]), (list[1][0]), (list[1][1]), (list[2][0]), (list[2][1]), (list[3][0]), (list[3][1]), colour, floor)
}
});

draggable d3 world globe in svelte

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>

SVG map zoom and center with fixed height

I'mt trying to implement zoom and center to the clicked element on the world map. The problem is, I want to achieve it with a fixed height, and don't know how should I calc this height to the viewbox. Here is my current solution on codepen:
const handleMapZoom = (e) => {
const map = document.getElementById('map');
const mapBounding = map.getBBox();
const targetBounding = e.getBBox();
const scale = Math.min(
mapBounding.width / targetBounding.width,
mapBounding.height / targetBounding.height,
4,
);
const transformOriginX = targetBounding.x + targetBounding.width / 2;
const transformOriginY = targetBounding.y + targetBounding.height / 2;
const transformOriginXPercent =
(50 - (transformOriginX * 100) / mapBounding.width) * scale;
const transformOriginYPercent =
(50 - (transformOriginY * 100) / mapBounding.height) * scale;
const scaleText = `scale(${scale})`;
const translateT = `translate(${transformOriginXPercent}%, ${transformOriginYPercent}%)`;
map.style.transform = `${translateT} ${scaleText}`;
e.style.fill = 'red'
};
https://codepen.io/abra-qyk/pen/XWpBqbj?editors=1111
What am I doing wrong? what is the problem with these calculations? I would be very grateful for help and explanation.

Simple problem svg `<image>` problem: repeating and not filling the space

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}

How to animate element along svg path on scroll?

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
>

Categories

Resources