Raphael path resize and move relative to container

前端 未结 1 1949
忘了有多久
忘了有多久 2021-01-25 23:25

I am trying to scale/move an SVG path created with the Raphael api. I want the path to fit neatly within a container, no matter the size of the container. I have searched the re

相关标签:
1条回答
  • 2021-01-26 00:09

    I think your problem is a fundamental misunderstanding of what the viewbox is useful for. In your code, you're attempting to set the viewbox of the svg element so that it matches the coordinate space of the screen, and then transform the path to match that coordinate space. There's no technical reason you can't do this, but it does effectively take the "Scalable" out of "Scalable Vector Graphics." The entire point of the viewbox is to make the translation between the vector coordinate space and the screen relative.

    The best way to solve your problem, then, is not to transform the path to match the SVG element, but to use the viewbox to let SVG's intrinsic scalability do this for you.

    First things first: create your path so we have an object to work with. We don't care what the viewbox is at this point.

    var pathStr = "...";  // The content of the path and its coordinates are completely immaterial
    
    var path = paper.path(pathStr)
        .attr({ fill: "#000", "stroke-width": 0, "stroke-linejoin": "round", opacity: 1 });
    

    Now all we need to do is use the viewbox to "focus" the SVG on the coordinate space we're interested in.

    var box = path.getBBox();    
    var margin = Math.max( box.width, box.height ) * 0.1;  //  because white space always looks nice ;-)
    paper.setViewBox(box.x - margin, box.y - margin, box.width + margin * 2, box.height + margin * 2);   
    

    And that's it. The SVG (regardless of its size) will translate from the internal coordinates specified in the viewbox to its physical coordinates on screen.

    Here's a fork of your fiddle as proof-of-concept.

    0 讨论(0)
提交回复
热议问题