You are lucky that I just did it myself. I am using jQuery SVG plugin ( http://keith-wood.name/svg.html )
$("#paper2").mousedown(function(ev) { ev.preventDefault(); var pX= (ev.pageX - this.offsetLeft) * viewBox[2]/parseInt($("#paper2").css("width")); var pY= (ev.pageY - this.offsetTop) * viewBox[3]/parseInt($("#paper2").css("height")); var rect = svg2.rect( pX, //X pY, //Y 1,1, //width and height { //Settings, you can make the box dotted here fill: 'black', "fill-opacity": 0.3, stroke: 'red', strokeWidth: 3, id:rect } ) $("#paper2").mousemove(function(ev) { ev.preventDefault(); var rect= $('#rect'); var pX= (ev.pageX - this.offsetLeft) * viewBox[2]/parseInt($("#paper2").css("width")) - rect.attr("x"); var pY= (ev.pageY - this.offsetTop) * viewBox[3]/parseInt($("#paper2").css("height")) - rect.attr("y"); rect.attr("width", pX); rect.attr("height", pY); }); $("#paper2").mouseup(function(ev) { ev.preventDefault(); var div= $("#paper2"); div.unbind('mousemove'); div.unbind('mouseup'); }) });
paper2 is the div in which I have the svg element (so the svg element and div have the same height / width). This is how I created the svg2 element:
var svg2; var root2; $(document).ready(function() { $("#paper2").svg({ onLoad: function() { svg2= $("#paper2").svg('get'); svg2.configure({id: 'svg2'}); var div= $("#paper2"); root2= svg2.root(); $("#svg2").attr("viewBox", viewBox[0]+','+viewBox[1]+','+viewBox[2]+','+viewBox[3]); }, settings: {} }); }
If you are not using viewbox on the svg element, you do not need this in calculations:
* viewBox[2]/parseInt($("#paper2").css("*****"));
viewbox [2] will be the width of the viewport, and viewbox [3] will be the height of the viewbox.
source share