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 reference, the web and I'm still struggling to get this to work.
If anyone can tell me why this isn't working, I would be very happy.
This fiddle shows you what I'm doing: 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>
Thanks, Torgeir.