SVG Image viewbox resizing - reactjs

I have this code that you can run below in the snippet. My issue is that in my production environment I have 2 SVGs, one on top of the other, each containing all sorts of content. When the user clicks on either side of the header, as seen in the snippet, the SVG that is on top should grow or shrink to either show more or less of the SVG underneath (I know this isn't perhaps performant with regards to the SVG potentially being drawn beneath - but my question likely involves this, as the answer probably has something to do with a lack of understanding of SVG viewbox on my part).
The issue is that because I want the images contents to remain the same size as the SVG on top grows or shrinks I decided to use Greensock in order to animate the grow/shrink of both the width AND the viewbox. This though causes very nasty glitching - in the snippet, run the code and click the Black box (pay attention especially to the bottom left corner of the image, but also to the jumps in the leftmost circle)!
Am I mistaken in changing both? Is there a way to only alter the width? Would this still cause the glitch as seen below?
Appreciate your help!
class Header extends React.Component {
constructor(props) {
super(props);
this.leftPanel = null;
this.leftPanelTween = null;
this.rightPanel = null;
this.rightPanelTween = null;
}
slideLeftHandler = () => {
this.leftPanelTween = TweenMax.to(this.leftPanel, 2, {width: '100%', attr: {viewBox: "0 0 500 150"}});
};
slideRightHandler = () => {
this.rightPanelTween = TweenMax.to(this.leftPanel, 2, {width: 0, attr: {viewBox: "0 0 0 150"}});
};
render() {
return (
<div class="Header">
<svg width="100%" viewBox="0 0 500 150" ref={el => this.rightPanel = el} onClick={this.slideRightHandler}>
<rect id = "middle" width="100%" height="100%" fill="black">
</rect>
<circle cx="400" cy="75" r="25" fill="red">
</circle>
<circle cx="100" cy="75" r="25" fill="red">
</circle>
</svg>
<svg width="50%" viewBox="0 0 250 150" ref={el => this.leftPanel = el} onClick={this.slideLeftHandler}>
<rect id = "middle" width="100%" height="100%" fill="red">
</rect>
<circle cx="100" cy="75" r="25" fill="black">
</circle>
<circle cx="400" cy="75" r="25" fill="black">
</circle>
</svg>
</div>
);
}
}
ReactDOM.render(
<Header />,
document.getElementById('app')
);
.Header {
margin: 0;
cursor: pointer;
}
.Header svg {
position: absolute;
}
.Header .leftPanel {
top: 0;
left: 0;
}
.Header .rightPanel {
top: 0;
right: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/TweenMax.min.js"></script>
<div id="app"></div>

Animating the viewBox is not performant. I recommend making the SVG as large as it needs to be at the end all of the time and just animate the width of the rectangle within the SVG that was clicked.

Related

make SVG document responsive with the viewbox based on aspect ratio

I have created this codesandbox to illustrate the problem.
I have this ResponsiveSVG component:
export function ResponsiveSVG({
height,
width,
children,
origin = { x: 0, y: 0 },
preserveAspectRatio = "xMidYMid meet",
innerRef,
className,
...props
}: ResponsiveSVGProps): JSX.Element {
const aspect = height === 0 ? 1 : width / height;
const adjustedHeight = Math.ceil(width / aspect);
return (
<div
data-testid="cutting-svg-container"
style={{
position: 'relative',
overflow: 'visible',
height: '1px',
}}
>
<svg
style={{ overflow: 'visible' }}
className={className}
preserveAspectRatio={preserveAspectRatio}
width={width}
height={adjustedHeight}
viewBox={`${origin.x} ${origin.y} ${width} ${height}`}
ref={innerRef}
{...props}
>
{children}
</svg>
</div>
);
}
I would like my ResponsiveSVG component to know how to fit its content to the full width of the container while keeping the aspect ratio the same.
In the example I have a circle as a child of the svg document:
<ResponsiveSVG width={width} height={height}>
<circle cx={width / 2} cy={height / 2} r={radius} />
</ResponsiveSVG>
On desktop, it looks like this:
But in mobile view, it looks like this:
My calculations make the viewBox width and height the same as the actual width and height I am passing in, so no change happens.
The viewBox coordinates are exactly the same as the viewport.
Passing the width and height of the containing element to the viewBox is actually the wrong direction. viewBox defines the canvas on which the svg content elements are drawn: if you draw a circle with r="50", the viewBox width value must be at least 100, otherwise, it will never fit. If the center is at cx=50, the viewBox x value must not be greater than 0, otherwise the left side is cut off.
Responsiveness in SVG is achieved because there needs not to be any relation between the viewBox values and the width and height of the <svg> element. The canvas the child elements are drawn on is always fitted to the parent element dimensions.
In short, if all you want to achieve is to fit a circle in a <svg> element, choose a arbitrary radius r, set cx=cy=r and viewBox="0 0 2r 2r", and it will work. There is no need to know anything explicit about the parent size.
If you want your <svg> element to be the width of the container, set it so: width: 100%. The default height is auto, so no need to write that or preserveAspectRatio. It will size itself such that the canvas defined by viewBox fits itself.
<div
style="
position: relative;
overflow: visible;
height: 1px;
"
>
<svg
style="
width: 100%;
overflow: visible;
"
viewBox="0 0 100 100"
>
<circle cx="50" cy="50" r="50" />
</svg>
</div>

Draw a dashed path using Framer Motion in React

I'm trying to draw a dashed path, or at least give that illusion, using Framer Motion. Think animating a foot path on a treasure map. Animating the path length seems to be a common method, and so I've implemented it like below.
<motion.span
initial={{ pathLength: 0 }}
animate={{ pathLength: 1 }}
d="...a list of coordinates"
stroke="#000"
strokeWidth="5"
strokeDasharray="8"
/>
But it appears animating the path length doesn't work well with strokeDasharray. When I add the strokeDasharray value using the attribute, the path length animates but the strokeDasharray value, when inspected, reads 2000px instead of 8px. And when I add the strokeDasharray using CSS or inline styling, the path is dashed correctly, but the animation doesn't work.
From what I've read, strokeDasharray uses the path length when doing it's computations, so I'm guessing the initial "0" value is throwing things off. Might be way off. I don't know.
Is there a simple fix here? Or should I reassess how I go about the animation? Thank you!
Not a solution using Framer Motion, but found this pen by Ruskinz that does the job using some css animation. The HTML looks like this:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="340" height="333" viewBox="0 0 340 333">
<defs>
<path id="path1" d="M66.039,133.545c0,0-21-57,18-67s49-4,65,8s30,41,53,27s66,4,58,32s-5,44,18,57s22,46,0,45s-54-40-68-16s-40,88-83,48s11-61-11-80s-79-7-70-41 C46.039,146.545,53.039,128.545,66.039,133.545z" />
<mask id="mask1"><use class="mask" xlink:href="#path1"></mask>
</defs>
<use class="paths" xlink:href="#path1" mask="url(#mask1)" />
</svg>
And the CSS looks like this:
.paths {
fill: none;
stroke: grey;
stroke-dasharray: 5;
stroke-width: 5;
stroke-linejoin: round;
}
.mask {
fill: none;
stroke: white;
stroke-width: 10;
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: dash 5s linear alternate infinite;
}
/* does not work in IE, need JS to animate there */
#keyframes dash {
from {
stroke-dashoffset: 1000;
}
to {
stroke-dashoffset: 0;
}
}
See the full pen at https://codepen.io/elliz/pen/prYqwx
I had the same issue because i wanted to animate it with framer-motion and not in css. What i just did is i just put an exact copy of the path with the dashedArray line below the path which i'm going to animate.
It will act as an overlay. I just gave it the stroke color of the background and tweaked the stroke-width. I don't know how it would be with a linearGradient background. But in my case with a static background color it worked.
import { motion } from 'framer-motion';
export default function Path({ pathColor, bg }) {
return (
<svg
width="245.24878"
height="233.49042"
viewBox="0 0 64.888737 61.777671"
version="1.1"
id="svg1033">
<defs
id="defs1030" />
<g
id="layer1"
transform="translate(-20.472293,-22.027827)">
<g
id="g484"
transform="translate(11.886667,6.306109)"
>
<motion.path
initial={{ pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{
pathLength: { delay: 0.4, type: "tween", duration: 3, bounce: 0 }
}}
stroke={pathColor}
strokeDasharray='3.846, 1.282'
strokeDashoffset='0'
strokeWidth='0.641'
style={{ fill: 'none', fillRule: 'evenodd', strokeLinejoin: 'round' }}
d="m 70.258127,15.782623 c 0,0 -1.867161,10.194243 -5.854843,12.473363 -9.471023,5.413069 -22.204956,-6.41444 -32.583479,-3.054701 -9.553598,3.092694 -21.015474,9.948708 -22.6557013,19.855557 -1.7758628,10.726077 5.8258513,25.311914 16.2917403,28.255989 11.258271,3.166974 19.313188,-18.990719 30.80157,-16.800859 5.208004,0.992724 10.182339,12.218805 10.182339,12.218805"
id="path1154"
/>
<path
stroke={bg}
strokeDasharray='3.846, 2.282'
strokeDashoffset='0'
strokeWidth='1.641'
style={{ fill: 'none', fillRule: 'evenodd', strokeLinejoin: 'round' }}
d="m 70.258127,15.782623 c 0,0 -1.867161,10.194243 -5.854843,12.473363 -9.471023,5.413069 -22.204956,-6.41444 -32.583479,-3.054701 -9.553598,3.092694 -21.015474,9.948708 -22.6557013,19.855557 -1.7758628,10.726077 5.8258513,25.311914 16.2917403,28.255989 11.258271,3.166974 19.313188,-18.990719 30.80157,-16.800859 5.208004,0.992724 10.182339,12.218805 10.182339,12.218805"
id="path1155"
/>
</g>
</g>
</svg>
);
}

Manipulate svg circle origin to create rotation animation around center

I have a loader (spinner) drawn on a page via two <circle />. Need to spin both paths in a different direction with origin centered, so, circles spin around the center of an SVG and don't translate, per say.
Trying to animate it transform: rotate(360deg). Paths go haywire and have origin somewhere else. Tried managing viewBox for intended results and didn't succeed.
import React, { PureComponent } from 'react';
import styled from 'styled-components';
import { prop } from 'styled-tools';
class Loader extends PureComponent {
render() {
return (
<Spinner
xmlns="http://www.w3.org/2000/svg"
width="200"
height="200"
preserveAspectRatio="xMidYMid"
viewBox="0 0 100 100"
>
<circle
className='outer'
cx="50"
cy="50"
r="40"
fill="none"
stroke="#374a67"
stroke-dasharray="63 63"
stroke-linecap="round"
stroke-width="4"
/>
<circle
className='inner'
cx="50"
cy="50"
r="35"
fill="none"
stroke="#d50000"
stroke-dasharray="55 55"
stroke-dashoffset="55"
stroke-linecap="round"
stroke-width="4"
/>
</Spinner>
)
}
}
const Spinner = styled.svg`
& .outer {
animation: rotate 2s linear infinite;
}
& .inner {
animation: reverseRotate 2s linear infinite;
}
#keyframes rotate {
100% {
transform: rotate(360deg);
}
}
#keyframes reverseRotate {
100% {
transform: rotate(-360deg);
}
}
`;
export default Loader;
Don't know how to make an actual working snippet out of my piece of code, sry
Here's an example of my current animation:
You need to set the transform-origin in the center of your svg. However you may do it differently. Instead of animating the transform you may animate the stroke-dashoffset like this:
.outer {
stroke-dashoffset:0;
animation: rotate 2s linear infinite;
}
.inner {
animation: reverseRotate 2s linear infinite;
}
#keyframes rotate {
100% {
stroke-dashoffset:126px;
}
}
#keyframes reverseRotate {
100% {
stroke-dashoffset:-55px;
}
}
svg{border:1px solid}
<svg xmlns="http://www.w3.org/2000/svg"
width="200"
height="200"
preserveAspectRatio="xMidYMid"
viewBox="0 0 100 100"
>
<circle
class='outer'
cx="50"
cy="50"
r="40"
fill="none"
stroke="#374a67"
stroke-dasharray="63"
stroke-linecap="round"
stroke-width="4"
/>
<circle
class='inner'
cx="50"
cy="50"
r="35"
fill="none"
stroke="#d50000"
stroke-dasharray="55"
stroke-dashoffset="55"
stroke-linecap="round"
stroke-width="4"
/>
</svg>
Welcome to Stack.
You need to make a few small tweaks to get it working.
Just use one animation that goes from 0% to 100%.
Animate from 0deg to 360deg
#keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
For the reverse animation, you can reverse the direction using
animation-direction: alternate; in your CSS

Position SVG path under image with dynamic height

I'm trying to position a custom path underneath images that are being loaded, the images will have the same width but the height will vary.
I'm using react-measure to get width, height of my image in svg to later on use that height to position the next element, but due to presumably aspect ratio, I get wrong values.
<svg viewBox="0 0 1000 2000">
<svg
x="150"
y="200"
>
<Measure
bounds
onResize={ (contentRef) => {
this.setState(prevState => ({ imgDimensions: contentRef.bounds }));
} }
>
{ ({ measureRef }) => (
<svg x="0">
<image className={ classes.img } ref={ measureRef } width="200" xlinkHref={ image } />
</svg>
) }
</Measure>
<rect x="5" y={ this.state.imgDimensions.height } height="2" width={ width } />
</svg>
</svg>
Example values:
imgDimensions:
bottom: 504.6000061035156
height: 176.39999389648438
left: 595
right: 835
top: 328.20001220703125
width: 240
and how it's positioned:
https://imgur.com/a/o4bbFG2
That black line should be exactly where the image ends.
But if I resize the website and refresh it - this is what I get: https://imgur.com/a/n9sxTic

How to animate svg picture after a button click in React

I'm building a simple App in react. And I'm trying to change an svg fill color when I click on like button. I've researched around and many developers use React Transition Group as a way, but I'm having hard time understanding how it works in this case.
Each time I click on like button, it increments the number and I want to change the color of svg background when it does. I've tried this way but it doesn't work. What am I doing wrong here?
Here is code.
<button onClick={this.props.increment.bind(null,index)}>
<span>{this.state.portfLikes}</span>
<CSSTransition
key="heart"
classNames="anim"
timeout={{ enter: 500, exit: 300 }}>
<span className="like-icon" key="heart-icon"><Like/></span>
</CSSTransition>
</button>
Like svg as a component.
import React from 'react'
class Like extends React.Component{
render() {
return (
<svg viewBox="0 0 64 64" width="64px" xmlns="http://www.w3.org/2000/svg">
<g id="Layer_1"><g><circle cx="32" cy="32" fill="#a3bed7" r="32"/></g><g opacity="0.2"><g><path d="M49.982,31.003c-0.094-5.522-4.574-10.442-10.107-10.442c-3.2,0-6.019,1.674-7.875,4.131 c-1.856-2.457-4.676-4.131-7.875-4.131c-5.533,0-10.012,4.921-10.107,10.442H14c0,0.034,0.007,0.065,0.007,0.099 c0,0.025-0.007,0.049-0.007,0.076c0,0.155,0.038,0.272,0.045,0.421c0.495,14.071,17.813,19.84,17.813,19.84 s17.572-5.762,18.092-19.818C49.959,31.464,50,31.34,50,31.178c0-0.027-0.007-0.052-0.007-0.076c0-0.036,0.007-0.065,0.007-0.099 H49.982z" fill="#231F20"/></g></g><g><g><path d="M49.982,29.003c-0.094-5.522-4.574-10.442-10.107-10.442c-3.2,0-6.019,1.674-7.875,4.131 c-1.856-2.457-4.676-4.131-7.875-4.131c-5.533,0-10.012,4.921-10.107,10.442H14c0,0.034,0.007,0.065,0.007,0.099c0,0.025-0.007,0.049-0.007,0.076c0,0.155,0.038,0.272,0.045,0.421c0.495,14.071,17.813,19.84,17.813,19.84 s17.572-5.762,18.092-19.818C49.959,29.464,50,29.34,50,29.178c0-0.027-0.007-0.052-0.007-0.076c0-0.036,0.007-0.065,0.007-0.099 H49.982z" fill="#f5f5f5"/></g></g></g><g id="Layer_2"/></svg>
)
}
}
export default Like
CSS
Note: I've picked opacity as a test to see if the animation works.
.anim-enter {
opacity: 0.12;
}
.anim-enter.anim-enter-active svg {
opacity: 0.5;
transition: opacity 500ms ease-in;
}
.anim-exit {
opacity: 1;
}
.anim-exit.anim-exit-active {
opacity: 0.01;
transition: opacity 300ms ease-in;
}
I'm also open to suggestions about other performance friendly react animation tools.
I see Sebastian has already provided an answer for using css styles and the hover pseudo element. It did seem like you wanted it to happen on a click though.
CSSTransition is only really needed when you want to animate elements as they are added to the DOM. If the items already exist, you just use all the typical css jazz to animate items (transitions and transforms).
Here is an example using react lifecycle functions to add an event listener and animate the heart when a button is clicked.
See the codepen here https://codepen.io/bluesixty/pen/gGzbrj?editors=0111.
Note: there is something goofy with codepen in the callback on the eventlistener. Codepen is not calling animatingDone to change the state back to false. (I tested on my local and it works correctly). Just refresh the window to reset it.
Javascript
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
animate: false
};
}
//------------------------------------------------------------------------
// Handle the click animations
//------------------------------------------------------------------------
componentDidMount() {
const svgToPulse = this.itemToPulse;
svgToPulse.addEventListener("animationend", this.animatingDone);
}
componentWillUnmount() {
const svgToPulse = this.itemToPulse;
svgToPulse.removeEventListener("animationend", this.animatingDone);
}
animatingDone() {
this.setState({ animate: false });
}
pulse() {
this.setState({ animate: true });
}
render() {
return (
<div>
<button onClick={() => this.pulse()}>Clicky</button>
<svg
ref={e => {
this.itemToPulse = e;
}}
className={this.state.animate ? " animate-pulse" : ""}
viewBox="0 0 64 64"
width="64px"
xmlns="http://www.w3.org/2000/svg"
>
<g id="Layer_1">
<g>
<circle cx="32" cy="32" fill="#a3bed7" r="32" />
</g>
<g opacity="0.2">
<g>
<path
d="M49.982,31.003c-0.094-5.522-4.574-10.442-10.107-10.442c-3.2,0-6.019,1.674-7.875,4.131 c-1.856-2.457-4.676-4.131-7.875-4.131c-5.533,0-10.012,4.921-10.107,10.442H14c0,0.034,0.007,0.065,0.007,0.099 c0,0.025-0.007,0.049-0.007,0.076c0,0.155,0.038,0.272,0.045,0.421c0.495,14.071,17.813,19.84,17.813,19.84 s17.572-5.762,18.092-19.818C49.959,31.464,50,31.34,50,31.178c0-0.027-0.007-0.052-0.007-0.076c0-0.036,0.007-0.065,0.007-0.099 H49.982z"
fill="#231F20"
/>
</g>
</g>
<g>
<g>
<path
d="M49.982,29.003c-0.094-5.522-4.574-10.442-10.107-10.442c-3.2,0-6.019,1.674-7.875,4.131 c-1.856-2.457-4.676-4.131-7.875-4.131c-5.533,0-10.012,4.921-10.107,10.442H14c0,0.034,0.007,0.065,0.007,0.099c0,0.025-0.007,0.049-0.007,0.076c0,0.155,0.038,0.272,0.045,0.421c0.495,14.071,17.813,19.84,17.813,19.84 s17.572-5.762,18.092-19.818C49.959,29.464,50,29.34,50,29.178c0-0.027-0.007-0.052-0.007-0.076c0-0.036,0.007-0.065,0.007-0.099 H49.982z"
fill="#f5f5f5"
/>
</g>
</g>
</g>
<g id="Layer_2" />
</svg>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
And the css
.animate-pulse {
animation: animate-pulse 300ms;
}
#keyframes animate-pulse {
0% {transform: scale(1.2)}
50% {transform: scale(1.5)}
100% {transform: scale(1.2)}
}
How it works
Clicking the button sets the animate state to true
React responds to the state change and the animate-pulse class is added to the svg element
the eventlistener waits for the animation to end and makes the call to set the animate state back to false.
react responds to the state change and removes the animate-pulse class
You might try vanilla CSS - see this simplified example with a button:
<button>
<svg height="20" width="20"><circle cx=10 cy=10 r=8 /></svg>
</button>
per se, it's just a button with a circle. I format this using CSS:
button circle {
fill: yellow;
}
as soon as I extend the CSS to do an animation on focus, I think I already achieve what you are looking for
button circle {
fill: yellow;
transition: fill 2s;
}
button:focus circle {
fill: green;
}
The button changes from yellow to green when clicked. Instead of focus, you could also assign CSS classes.
I've put the exact same code into a codepen if you want to try directly: https://codepen.io/sebredhh/pen/NaMPoP

Resources