svg + Sprite sheet + d3 + clipPath + position + size

后端 未结 2 1167
Happy的楠姐
Happy的楠姐 2021-02-09 06:07

Need to apologize in advance: for length and for my ignorance. I\'m trying to teach myself new concepts: d3.js and sprite sheets. The sprite sheet concept is simple to understan

2条回答
  •  半阙折子戏
    2021-02-09 06:38

    I'm not sure what's going on with example, but the problem with your element is that you're not translating the image so that the icon you want is at the (0,0) point of the SVG.

    This is what you need:

    
        
            
                
            
        
            
    
    

    Of course, if you're going to be making lots of icons and using them multiple places, I would suggest:

    1. defining the icons within a element, and then referencing them when needed with elements;
    2. using a element to position the image in each icon, so you only have to define the image url, height, and width once;
    3. nesting each image/use element within a element, and applying the clipping path to it, so that you only have to define the clipping path once (assuming all icons are the same size).

    Example here: http://codepen.io/AmeliaBR/pen/mwzBD

    Key code for defining the icons:

    
      
        
    
        
        
            
        
    
        
        
    
        
        
            
        
        
            
        
        
            
           
     
    

    Then you reference the icons like this:

    
            
    
    

    The viewBox attribute sets the internal dimensions for laying out the image and will be the same every time you use the icon; the height and width can be anything you want (although scaling down will of course look better than scaling up). If the height/width ratio doesn't match the icon, it will be squished or stretched, but you can prevent that with a preserveAspectRatio attribute.

    Now, on to d3. It will probably be easiest to define the SVG fragments that represent the icons ahead of time, possibly in a separate file, although you could construct that DOM dynamically. When you actually want to insert an icon, you

    For example, to add an inline icon image at the end of every element with the class "warning", you would do something like this:

    d3.selectAll(".warning")
        .append("svg")
          .attr("viewBox", "0 0 "+ iconWidth + " " + iconHeight)
          .style("display", "inline")
          .style("height", "1em")
          .style("width", (iconWidth/iconHeight) + "em")
        .append("use")
          .attr("xlink:href", "#warning");
    

    Of course, if you're using d3, you've probably got some data variable that tells you which icon to use, instead of a class, but you get the idea.

提交回复
热议问题