Resizing single shapes dynamically without scaling the whole SVG

后端 未结 5 1141
悲&欢浪女
悲&欢浪女 2021-02-01 22:58

I have an arrow as a SVG which\'s length I want to alter in response to the width of a wrapping DIV (for example).

All my previous attempts have led into this behavior (

5条回答
  •  忘了有多久
    2021-02-01 23:39

    As a general rule, there is no way to create a scalable SVG where parts of it don't scale. If an SVG has a viewBox, and you scale it, then all the contents will scale. There is no way to mark some of the contents as immune to the scaling.

    The nearest you can get is to restrict scaling to the X axis. However the arrowhead will still stretch.

    
    
            
                
                
                
            
    
    
    
    
    
            
                
                
                
            
    

    If you want a generalised solution, then you have to monitor resize events and update the SVG dynamically.

    The limited sneaky clever solution...

    Having said all that, there is a clever technique that works in a limited set of circumstances. The limitations are:

    1. The SVG stretches in only one direction.
    2. The "non-scaling" parts are at either or both ends of the stretch
    3. The end parts are solid and don't have any holes.
    4. You are okay with the background of the SVG being a solid color, rather than transparent.

    Here is a demo of your shape implemented using this technique. If you resize the window horizontally, you'll see it stretches appropriately.:

    
    
      
        
        
      
        
      
        
      
    
      
        
        
      
    
    

提交回复
热议问题