Reputation: 325
With Snap SVG I am trying to create an rect dynamically.
When I click, it should create a rect at the position of the mouse click.
it's create the rect, BUT the postion is always wrong.
Here is my script : http://jsfiddle.net/noteStylet/L2kpd6yt/
So My question is Who to create a rect at the mouse click postion and not below.
HTML :
<h1>Click to create </h1>
<div>
<svg id="plan" width="900" height="500"></svg>
</div>
Javascript :
var snap = Snap("#plan");
//create an image
var imagePlan = snap.image("http://upload.wikimedia.org/wikipedia/commons/4/42/Cathedral_schematic_plan_fr_vectorial.svg", 10, 10, 900, 500);
imagePlan.click(function (evt) {
//When click, create a rect
var rect1 = snap.rect(evt.clientX, evt.clientY, 40, 40);
});
Thanks !
Upvotes: 1
Views: 629
Reputation: 121
Your problem is the grid system of the svg you need to re-abjust it so that your mouse is not the (0,0) but rather the (-20,-80). change the rect creation code to :
var rect1 = snap.rect(evt.clientX-20, evt.clientY-80, 40, 40);
and it should work
update:
Ok so what you need is 1.get mouse position and 2.the position of the image ( left & top values). Then subtract them from current mouse position so you can adjust the svg grid to feet your needs
var snap = Snap("#plan");
//create an image
var imagePlan = snap.image("http://upload.wikimedia.org/wikipedia/commons/4/42/Cathedral_schematic_plan_fr_vectorial.svg", 10, 10, 900, 500);
var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function(event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
var image = $( "#plan" );
var position = image.position();
imagePlan.click(function()
{
//When click, create a rect
var rect1 = snap.rect(currentMousePos.x-position.left ,currentMousePos.y-position.top, 40, 40);
});
});
Upvotes: 0
Reputation: 325
We should use this method :
var transformed = pt.matrixTransform(mySvg.getScreenCTM().inverse());
var rect1 = s.rect(transformed.x, transformed.y, 40, 40);
instead of
var rect1 = snap.rect(evt.clientX, evt.clientY, 40, 40);
We have to use :
var mySvg = $("#svg1")[0];
var pt = mySvg.createSVGPoint(); // create the point;
imagePlan.click(function(evt)
{
pt.x = evt.x;
pt.y = evt.y;
// convert the mouse X and Y so that it's relative to the svg element
var transformed = pt.matrixTransform(mySvg.getScreenCTM().inverse());
var rect1 = s.rect(transformed.x, transformed.y, 40, 40);
});
Here is the Example : http://jsfiddle.net/noteStylet/L2kpd6yt/6/
Upvotes: 1