Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do with SVG so it can be resized using Javascript?

Tags:

javascript

svg

Let's say I loaded SVG, displayed it in browser, and so far it is OK.

Now, I would like to resize it. All methods I found googling failed to give me the desired effect.

It is all variations of:

$svg.removeAttr('width')
    .removeAttr('height')
  //.attr('preserveAspectRatio','xMinYMin meet')
  //.css('width',width+'px')
  //.css('height',height+'px')
    .css('width','100%')
    .css('height','100%')
    .attr('viewBox','0 0 '+width+' '+height)
    ;

Nothing. I get the view of desired size, but the image (SVG) is clipped to that view instead of being resized. Setting size via attributes does not change a thing. Like the size of that SVG is carved in stone.

Thanks to frenchie answer (see below) it appears JS tries hard to resize SVG and for basic SVG it just works. So the real question is -- what to do with SVG (real-world SVG, not just a rectangle) so Javascript would be able to resize it?

SVG I am testing: http://jsfiddle.net/D6599/


I created SVG with Inkscape, and this is how I load SVG in JS:

$.get(svg_url, function(data) {
    // Get the SVG tag, ignore the rest
    svg = $(data).find('svg')
            .attr('id', 'SVG')
            // Remove any invalid XML tags as per http://validator.w3.org
           .removeAttr('xmlns:a')
           [0];

    on_load();
}, 'xml');

The code comes from How to change color of SVG image using CSS (jQuery SVG image replacement)?. What I have later on is svg element (I wrapped it using jQuery).

This is not the question how to load SVG, or what to do with cross-domain issue. SVG loads fine, it is the same domain as the script (my disk).

like image 435
greenoldman Avatar asked Dec 06 '25 23:12

greenoldman


1 Answers

Your SVG markup should look like this:

<svg id="SomeID" height="20" width="20">......</svg>

So all you need to do is reset the css properties. Something like this should work:

$('#SomeID').css({'width':40, 'height' :40});

And if you can't change the id of the SVG markup then you can simply wrap it around a div like this:

<div id="SomeID"><svg>....</svg></div>

$('#SomeID').find('svg').css({'width': 40, 'height': 40});

Here's a jsFiddle:

function Start() {  
    $('#TheButton').click(ResizeSVG);    
};

function ResizeSVG() {    
    $('#TheSVG').css({'width':40, 'height' :40});
}

$(Start);
like image 116
frenchie Avatar answered Dec 09 '25 14:12

frenchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!