Scaling SVG Graphics in Real-Time

I am currently developing a website where users can interact with an SVG image using textboxes. One of my goals is to make sure the SVG image scales to fit the container div.

For example, if the SVG was the same height as the container but only 10 pixels wide, doubling the height would make the width appear to be 5 pixels.

My webpage layout consists of numbers on the left side and the image on the right side. As a result, resizing the browser changes the shape of the SVG's container element, making it difficult to set fixed dimensions for the container in the SVG code.

Although I have searched online for solutions involving the use of the viewBox attribute, I have not been able to find a way to implement it without specifying a hard-coded container size.

Feel free to check out this fiddle with my editor setup:

https://jsfiddle.net/xyjs5b63/

Answer №1

It seems like adjusting the viewBox might be the solution you're looking for. I'm not entirely sure why it didn't work before.

var svg = document.querySelector('svg');

var inputs = document.querySelectorAll('input');

var height_elem = inputs[0];
var width_elem = inputs[1];

height_elem.value = '100';
width_elem.value = '100';

height_elem.addEventListener("change", valueChange);
width_elem.addEventListener("change", valueChange);

function valueChange() {
    svg.setAttribute('viewBox', "0 0 "+width_elem.value+" "+height_elem.value);
}

valueChange();
#out {
    width: 100px;
    height: 100px;
    background-color: honeydew;
}

svg {
  width: 100%;
  height: 100%;
}
<div id="main">
    <div id="in">
        <input type="number"><br>
        <input type="number">
    </div>
    <div id="out">
        <svg>
            <rect width="100%" height="100%"></rect>
        </svg>
    </div>
</div>

Answer №2

var rectangle = document.querySelector('rect');
var drawing = document.querySelector('svg');

var inputs = document.querySelectorAll('input');

var height_input = inputs[0];
var width_input = inputs[1];

height_input.value = '100';
width_input.value = '100';

height_input.addEventListener("change", inputChange);
width_input.addEventListener("change", inputChange);

function inputChange() {
    var max = parseInt(height_input.value) >= parseInt(width_input.value) ? 'h' : 'w';
    if (max == 'h') {
        rectangle.setAttribute('height', "100%");
        rectangle.setAttribute('width', (width_input.value * 100 / height_input.value)+"%");
    } else {
        rectangle.setAttribute('width', "100%");
         rectangle.setAttribute('height', (height_input.value * 100 / width_input.value)+"%");
        }
}

inputChange();
#container {
    width: 100%;
    padding: 0;
}

#inside {
    float: left;
    width: 40%;
    height: 100%
}

#outside {
    margin: 10%;
    width: 20vw;
    height: 20vw;
}

svg {
    width: 100%;
    height: 100%;
}
<div id="container">
<div id="inside">
    Height: <input type="number"><br>
    Width: <input type="number">
</div>
<br>
<div id="outside">
    <svg height="auto">
    <rect></rect></svg>
</div>
</div>

Is this the solution you were looking for?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with margin and padding-top not functioning properly when using @media for printing

Is there a way to add some space between the top of my webpage and my logo? I've tried adjusting the padding in my CSS, but when I check the print preview in Chrome, no spacing is visible. Below is my HTML code: <div class="container"> < ...

jQuery functions smoothly on Firefox, but encountering issues on Chrome

While it may seem like a repetitive inquiry, I have thoroughly researched similar questions and have not found a suitable solution. The server is returning the following response through a standard ajax call: <form id="ctl00" name="ctl00" method="post ...

Steps to insert a Drop-Down Sub-Menu

I'm just about finished with my navigation panel. Any tips on how to add a sub-menu? I currently have one in the Product page. Below is the HTML code containing the sub-menus: <nav> <ul> <li><a href="">HOME</a>&l ...

How can I position two bootstrap tables side by side based on their columns

Currently, I am utilizing bootstrap and Laravel form control to generate the table structures below. The one issue I am encountering is figuring out how to align the delete and edit buttons from two separate tables. Here is a snapshot of the current layout ...

When applying a maximum width of 100% with automatic height, images may become cropped

I'm a beginner in learning CSS, and since my technical skills are limited, I'll try to keep things simple. Currently, I have an image taking up half of the screen with the following CSS code that I found after reading some articles: <div class ...

I'm having trouble with jQuery recognizing the left-margin property. Is there a workaround for this issue?

I rarely use jquery, but I wanted to add animation to a side bar. The sidebar menu is 670px with a -670 left-margin. When the user hovers over it, I'd like the left-margin to change to 0px and reveal the hidden content. Upon mouseout, it should return ...

Attempting to navigate the world of AJAX and PHP

My experience with AJAX is limited, but I am currently working on a project that requires a form to submit data without refreshing the page. The goal is to display the result in a modal window instead. To achieve this functionality, I understand that imple ...

Slider in MaterialUI featuring a vibrant spectrum of colors

Currently, I am delving into MaterialUI and my focus is on creating a range slider. I came across this example that I found useful: https://material-ui.com/components/slider/#range-sliders My goal is to assign different colors to the "high," "medium," and ...

The stylesheet malfunctioned while attempting to load varying layouts in separate controllers

Hey, I encountered a strange issue. After clicking on the three pages displayed in the images below: Step 1 controller welcome Step 2 other controllers Step 3, back to step 1 view controller welcome The final image, when returning to controller welcom ...

Is there a way to adjust the position of ::before elements without affecting the border placement?

I'm struggling with an element that has a CSS style ::before to display an arrow-up inside a black circle. Check out the code here The issue I'm facing is that the character \25b2 isn't centered vertically within the circle. Adjustin ...

The functionality for the "OnChange" event in the <html:select> field does not seem to be functioning properly

My JavaScript function isn't functioning properly. I can't see any alert messages on my webpage. Can someone please assist me? Below is my HTML code function checkProjectStatus() { alert("Helloo"); var dropdownType = document.getElementById( ...

Displaying a div in Vue.js when a button is clicked and an array is filled with

Hey there! I'm having an issue with displaying weather information for a specific location. I want to show the weather details in a div only when a button is clicked. Despite successfully fetching data from the API, I'm struggling to hide the wea ...

Is there a way to add additional text to a text element within an SVG?

Is it possible to append a new text element at the end of the data label by clicking on that particular text? I have attempted to implement this in my code but the additional text is not being displayed as expected: circleGroup.selectAll("text") ...

I'm looking for assistance in setting up a static sidebar within a two column layout. Any takers

Seeking assistance to fix the issue of making the right sidebar static when user begins scrolling. I am relatively new to responsive web design. I have attempted using the "position:fixed" property, but uncertain about its compatibility with responsive d ...

Unique background image tailor-made for each radio button

Looking to create radio buttons with buttonset that have unique icon backgrounds for each button. Open to options other than buttonset if available, but assuming it needs to be used. Key requirements: No radio button icon Rollover effect Icon background ...

Enhance the functionality of your website by implementing a zoom feature

I am looking to dynamically change the CSS of a div using jQuery when it is clicked. The challenge I am facing is that there are multiple divs with the same class and I am unable to modify their classes as they are created dynamically using PHP. <div ...

Displaying the result of a JavaScript function in a textarea

I've been working on getting this function to output to the textarea below. The current code functions correctly, but it displays the output on the whole page instead of in a text field. I know that the connection between the two is not properly estab ...

Bug in canvas rendering for Chrome versions 94 and 95

The Canvas drawing functionality in the Chrome browser seems to have some visible bugs. Here's an example of code that demonstrates this issue: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d&apo ...

Bootstrap: when divs cover the jumbotron

I have recently started exploring bootstrap and have been using it to build a homepage for my website. However, I am facing an issue: The three images are overlapping the jumbotron section and I can't seem to figure out why. Below is the HTML code sn ...

Can you please tell me the CSS combinator used for the selectors (foo bar, foo biz, foo tar, foo boo { })?

What is the CSS combination or shorthand for creating this ruleset? foo bar, foo biz, foo gaz > boo, foo tar { ... } I remember seeing on the MDN that there was a shorthand for this. Is it: foo (bar, biz, gaz > boo, tar) { } I am having troub ...