javascript - Fixing the canvas offset in Raphael.js when DOM element centered -
i'm creating circles in raphael.js canvas clicking action. when canvas drawn @ origin of website works fine. but when move middle type offseting happens , when click on right side of canvas circles drawn @ left side of canvas. though have listener action canvas , not div append to, here code:
<body> <div id="container"></div> </body>
here js:
var canvas = raphael("container", 500, 500); var ourcanvas = $('svg').last(); ourcanvas.attr("id", "canvas"); var canvashandler = $("#canvas"); //we create div class append our canvas var containerhandler = $("#container"); var circleclass = $("circle.quincy"); var justdragged = false; canvashandler.mouseup(function (e) { var mousex = e.pagex; var mousey = e.pagey; makecircle(mousex, mousey); }); function makecircle(mousex, mousey) { var radius; var fill; var thiscirclesid = string(new date().gettime()); var circle = canvas.circle(mousex, mousey, 50).attr({ fill: "hsb(.8, 1, 1)", stroke: "none", opacity: .5, }); }
here jsfiddle
i wonder if way i'm using event position correct. suggestion more welcome.
thanks
m
i figured out after realizing offset of new position of svg causing mouse event not recognize real position. found blog post shows how use offsetparent method calculate new position of canvas relative parent . here code:
$(document).ready(function () { //we create our canvas , add id var canvas = raphael("container", 500, 500); var ourcanvas = $('svg').last(); ourcanvas.attr("id", "canvas"); var canvashandler = $("#canvas"); //we create div class append our canvas var containerhandler = $("#container"); var circleclass = $("circle.quincy"); var justdragged = false; canvashandler.mouseup(function (e) { var mousex = e.pagex - findpos(this)[0]; var mousey = e.pagey - findpos(this)[1]; makecircle(mousex, mousey); findpos(this); console.log("this position of mouse in x: " + e.pagex); console.log("this position of mouse in y: " + e.pagey); }); function findpos(obj) { var curleft = curtop = 0; if (obj.offsetparent) { { curleft += obj.offsetleft; curtop += obj.offsettop; } while (obj == obj.offsetparent); console.log(curleft); console.log(curtop); // return [curleft, curtop]; } return [curleft, curtop]; }
as can see findpos(obj) returns , array of new position of x , y. substract mousex , mousey real position on svg when clicking.
update
doing more reading , asking around. didn't realize type of elements web browser returns. instead of using e.pagex , e.pagey. offsetx offers position of mouse in respect parent giving real coordinates. code this:
canvashandler.mouseup(function (e) { var mousex = e.offsetx; var mousey = e.offsety; makecircle(mousex, mousey); findpos(this);
});
this makes easier since offset takes consideration real position of mouse in respect element.
Comments
Post a Comment