Home > front end >  Responsive SVG with fitting image in HTML/CSS/JS
Responsive SVG with fitting image in HTML/CSS/JS

Time:10-07

I have two issues about responsiveness, I'll try to explain my situation as clear as possible, please don't hesitate to ask for any details if needed.

I have the following SVG which simulates a simple design of a screen printing machine from a top view.

Screen Printing Machine

Each of those frames should have a <div></div> inside with some images stacked on absolute position to make some sort of before&after gallery. The SVG is shown in this way:

UI Design

When the user clicks any of the arrow icons, the SVG rotates 90deg to show the next or previous image. I made this work with some CSS and simple JS. I also got to position the image frame perfectly on top of the SVG. The issue is that as soon as the window is resized, the images stop matching the width and height of the frames, and the SVG loses its position going either too much to the top or too much to the bottom. I'm using mainly percentages to position almost everything here, but I know that this isn't the best way to go for this solution.

How can I achieve a responsive wrapper that sets the SVG halfway at the top and maintains the bottom frame visible as shown in the UI Design? How can I make the image frame resize as the SVG grows or shrinks? I'd appreciate your help, thanks in advance.

Here's a Fiddle: https://jsfiddle.net/EvreuxPendragon/zcbm0n46/8/

CodePudding user response:

I'm sure there are a number of ways to handle this (there always are), but I came up against a similar problem recently and I implemented it using SVG <image> elements in the SVG. The advantage of this approach is that the image element is sized and positioned using SVG viewbox coordinates, which grows and shrinks with the SVG - so it stays correctly positioned within your SVG. As you do in your jsfiddle, you can change the image URL (href) using javascript.

Here's the page where I implemented the picture swapping within an SVG frame: https://fintellect.io/ease The phone frame is an SVG, and as the user scrolls and new text content becomes visible the image within the phone frame is changed.

You can view it in dev tools with mobile/responsive to see that the image is positioned sized correctly as the outer SVG resizes.

  • Related