Finding the absolute position of the paper/canvas in the Raphael JavaScript library
How can I find the absolute position of the paper/canvas when using the Raphael JavaScript library?
For instance, suppose the minimal working example is as follows:
<html>
<head>
<script type="text/javascript" src="raphael.js"></script>
<script>
window.onload = function() {
var size = 600;
var paper = new Raphael(document.getElementById("canvas_container"),
size, size);
var c = paper.circle(100, 100, 50).attr({fill: "#00f"});
var x = 0; // get the paper's absolute x coordinate
var y = 0; // get the paper's absolute y coordinate
开发者_如何学运维 document.getElementById("coordinates").innerHTML = x + " " + y;
};
</script>
<style type="text/css">
#canvas_container {
width: 600px;
margin-left: auto;
margin-right: auto;
border: 1px solid #aaa;
}
</style>
</head>
<body>
<p id="coordinates"></p>
<div id="canvas_container"></div>
</body>
</html>
How do I find the absolute x and y coordinates of the paper from the top of the page without knowing the ID of the div that it lives in? (In the example, I can know that, but my actual situation makes knowing the div ID much more complicated.)
OK. I see what it should be now:
var x = this.paper.canvas.offsetLeft;
var y = this.paper.canvas.offsetTop;
That seems to work correctly on both IE 8.0 and Chrome 9.0.
To get the abs position of your Raphael paper, you can use jQuery:
$(paper.canvas).offset()
The accepted solution doesn't worked for me, it gives me x = -1 and y = -1, so if someone has the same problem I solved it this way:
var x = paper.canvas.parentNode.offsetLeft;
var y = paper.canvas.parentNode.offsetTop;
精彩评论