Raphael路径调整大小并相对于容器移动

时间:2014-01-15 14:58:51

标签: javascript svg raphael

我正在尝试缩放/移动使用Raphael api创建的SVG路径。无论容器的大小如何,我都希望路径整齐地放在容器内。我已经搜索了参考文献,网络,我仍然在努力让这个工作起作用。

如果有人能告诉我为什么这不起作用,我会非常高兴。

这个小提琴告诉你我正在做什么:http://jsfiddle.net/tolund/3XPxL/5/

JavaScript的:

var draw = function(size) {
    var $container = $("#container").empty();
    $container.css("height",size+"px").css("width",size+"px");

    var paper = Raphael("container");

    var pathStr = "M11.166,23.963L22.359,17.5c1.43-0.824,1.43-2.175,"+
        "0-3L11.166,8.037c-1.429-0.826-2.598-0.15-2.598,"+
        "1.5v12.926C8.568,24.113,9.737,24.789,11.166,23.963z";

    // set the viewbox to same size as container
    paper.setViewBox(0, 0, $container.width(), $container.height(), true);

    // create the path
    var path = paper.path(pathStr)
        .attr({ fill: "#000", "stroke-width": 0, "stroke-linejoin": "round", opacity: 1 });

    // get the path outline box (may be different size than view box.
    var box = path.getBBox();

    // move the path as much to the top/left as possible within container
    path.transform("t" + 0 + "," + 0);

    // get the width/height based on path box relative to paper (same size as container)
    var w = (paper.width) / box.width;
    var h = (paper.height) / box.height;

    // scale the path to the container (use "..." to compound transforms)
    path.transform('...S' + w + ',' + h + ',0,0');
}

$(function() {
    var currentSize = 30;
    draw(currentSize);

    $("#smaller").click(function(){ 
        currentSize = currentSize < 10 ? currentSize : currentSize * 0.5;
        draw(currentSize);
    });
    $("#bigger").click(function(){ 
        currentSize = 300 < currentSize ? currentSize : currentSize * 2; 
        draw(currentSize);
    });
});

HTML:

<button id="smaller">-</button>
<button id="bigger">+</button>

<div id="container" style="border: 1px #ddd solid; margin: 30px">

</div>

谢谢, Torgeir。

1 个答案:

答案 0 :(得分:4)

我认为您的问题是对视图框有用的基本误解。在您的代码中,您尝试设置svg元素的视图框以使其与屏幕的坐标空间匹配,然后转换路径以匹配该坐标空间。没有技术上的理由你不能这样做,但它确实有效地从“可扩展矢量图形”中取出“可扩展”。视图框的整个点是在矢量坐标空间和屏幕相对之间进行平移。

解决问题的最佳方法是,不要转换路径以匹配SVG元素,而是使用视图框让SVG的内在可伸缩性为您完成此任务。

首先要做的是:创建你的路径,这样我们就有了一个可以使用的对象。我们现在不关心视图框是什么。

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 });

现在我们需要做的就是使用视图框将SVG“聚焦”在我们感兴趣的坐标空间上。

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);   

就是这样。 SVG(无论其大小)将从视图框中指定的内部坐标转换为屏幕上的物理坐标。

这是proof-of-concept的小提琴。

相关问题