Can't get mouse coordinates through javascript - javascript

Recently I have been trying to get a grasp of javascript. I've been experimenting through the past couple of months with different code to see what all is possible through javascript. Recently I've been trying to find various ways to capture the mouse coordinates through javascript with a canvas. Here's my attempt: http://jsfiddle.net/f8n2one4/
As you can see, there's a MouseHandler which is supposed to capture the mouse coordinates through the ClientX and ClientY variables. However, when I try to display these variables, nothing comes up. Why is that?
document.getElementById("test").innerHTML = "x: " + x + " y: " + y;
Shouldn't it show the x and y values?

The x and y variable are out of the scope of your draw() method.
try the following:
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
player();
MouseHandler.init(document);
var clientPosition = MouseHandler.getPos();
document.getElementById("test").innerHTML = "x: " + clientPosition.x + " y: " + clientPosition.y;
}
See it working here.
I would recommend not to initialize the whole MouseHandler every interval, just getting the position on every interval.
Also if you are animating use .requestanimationframe() instead of setInterval, you'll get better performance.

In your example are you are initializing the mouse handler (with MouseHandler.init(element)) but the x and y values have to be accessed using the getPos() method:
document.getElementById("test").innerHTML =
"x: " + MouseHandler.getPos().x +
" y: " + MouseHandler.getPos().y;
You can see a working update to your fiddle here

The x and y do not exist. You need to use:
document.getElementById("test").innerHTML = "x: " + MouseHandler.getPos().x + " y: " + MouseHandler.getPos().y;
Fiddle: http://jsfiddle.net/f8n2one4/3/

It's actually really simple, your x, y are out of scope.
You could access them via your MouseHandler variable :
MouseHandler.getPos().x
MouseHandler.getPos().y
Or try OOP Javascript and instantiating the MouseHandler with a 'new' operator
var MouseHandler = function() {
this.x = 0;
this.y = 0;
}
var myMouseHandler = new MouseHandler();
console.log(myMouseHandler.x + myMouseHandler.y);

Related

5.6.5 Coordinates, Answer In Comments (CodeHS)

The prompt of the assignment is "Write a program that shows the X and Y coordinates of the mouse in a label on the top left of the screen. You should update the values of the coordinates whenever the mouse moves." The basic code I have laid out is:
var pos;
function start(){
mouseMoveMethod(mousePos);
}
function mousePos(e){
pos = new Text("((" + e.getX() + "," + e.getY() + ")");
pos.setPosition(75, 75)
add(pos);
}
It "works" but it just keeps adding text over top of the new text instead of updating the existing text. I know I'm missing something, but I just cannot figure out what to implement to make it work the way it needs to. I've been stuck for days :(
I got it!!! I just needed to think smarter LOL
var pos;
function start(){
pos = new Text(" ");
pos.setPosition(75, 75)
add(pos);
mouseMoveMethod(mousePos);
}
function mousePos(e){
pos.setText("(" + e.getX() + "," + e.getY() + ")");
}

Get cursor position at frequent interval

I'm trying to get mouse cursor current position at frequent interval.
function checkMousePos(ev){
alert(true);
var x = ev.clientX,
y = ev.clientY;
alert('' + x + ' ' + y);
}
setInterval(checkMousePos, 500);
This code alerts true, but never x and y.
What am I not doing right ?
When debugging something you far better using something like console.log(myVariable) and then viewing it in the console. In your case ev not being pass by your interval and there for it's undefined. What seems like this:
var x;
var y;
document.addEventListener('mousemove', function(event){
x = event.pageX;
y = event.pageY;
})
function checkMousePos(){
console.log("Cursor at: " + x + ", " + y);
}
setInterval(checkMousePos, 500);
Although it's usually not the best solution.

Get crosshair values across multiple Flot Charts

I'm using the jQuery Flot Charts plugin in one of my projects. I have several charts standing in the same column and what I'm trying to do is: Show the crosshair on all of the charts if you hover on any of them. I'm doing this successfully using the following code.
//graphs - this is an object which contains the references to all of my graphs.
$.each(graphs, function(key, value) {
$(key).bind("plothover", function (event, pos, item) {
$.each(graphs, function(innerKey, innerValue) {
if(key != innerKey) {
innerValue.setCrosshair({x: pos.x});
}
});
if(item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
console.log("x:" + x + ", " + "y:" + y);
}
});
});
I'm iterating over the graphs, adding the crosshair and bind it to each other. So, now, when you hover over one of the graphs you'll see the crosshair in the same position on all of the others.
No problems with this. However I'm having problems with the second part of my code:
if(item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
console.log("x:" + x + ", " + "y:" + y);
}
And the problem is that I'm getting the console.log to print values only when I hover the actual point with my mouse while I want to get that value whenever the crosshair crosses that point, not necessarily the mouse pointer. Any clues what I'm doing wrong or maybe there's a setting in the graph options for that to work?
And another thing is that I can get the value for one graph only - the one my mouse is on, I don't seem to be able to get the values for the rest of the graphs where the crosshair is also moving.
The highlighting with
if(item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
console.log("x:" + x + ", " + "y:" + y);
}
only works when the cursor is near a point (otherwise item is null).
To get the nearest point to the crosshair, you have to do the highlighting manually by searching the nearest point and interpolate (for every graph). The code for that could look like this:
var axes = value.getAxes();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
return;
}
$('#output').html("x: " + pos.x.toPrecision(2));
$.each(graphs, function(innerKey, innerValue) {
var i, series = innerValue.getData()[0];
// Find the nearest points, x-wise
for (i = 0; i < series.data.length; ++i) {
if (series.data[i][0] > pos.x) {
break;
}
}
// Now Interpolate
var y,
p1 = series.data[i - 1],
p2 = series.data[i];
if (p1 == null) {
y = p2[1];
} else if (p2 == null) {
y = p1[1];
} else {
y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
}
$('#output').html($('#output').html() + "<br />" + "y (" + innerValue.getData()[0].label + "): " + y.toPrecision(2));
See this fiddle for a full working example. Some Remarks to the new code and fiddle:
has sine and cosine values as example data, so uses floating point numbers, change accordingly for int numbers and/or date values
uses a <p> element for output instead of the console
point-finding and interpolation code can be optimized further if needed (basic version here taken from the example on the Flot page)
works only if there is only one data series per graph

Raphael.js attr function sets wrong value

I'm implementing a drag and drop system with Raphael.js. For this, i'm storing the original x and y position on mousedown, and if there is a collision on mouseup, I want to reset the position to the original one. Here's the bit of code that does the resetting ("this" refers to the raphael object here):
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
What's weird is that after setting the attribute, the transform string changes by a couple pixels. I debugged this with:
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
console.log("transformString: " + transformString);
console.log("transformAttrib: " + this.attr("transform"));
AFAIK, both logged values should be equal in any case. But they are sometimes off by as much as 20px. Does anyone know what's going on here?
E: Here is a simplified version, without the collision testing, which still reproduces the bug: http://jsfiddle.net/6ozsfdaf
I'm not sure why this is happening. I tried even capturing the co-ordinates before onstart using onmousedown event, even that didnt work. Also different methods provided by Raphael to get the co-ordinates using getBBox(), accessing x and y directly, didnt help.
So what I thought is, we should Maintain and Track the coordinates manually. So I have used your original_x and original_y variables which captures the position of the <path> after you create and set with some transform value. Below is the code of the same
Here is the working fiddle.
this.raph = R.path(svgPath).attr({
stroke: "hsb(0, 1, 1)",
fill: "#fff",
opacity: 1.0,
cx: 100,
cy: 900
}).transform("t" + x + "," + y);
this.raph.original_x = x;
this.raph.original_y = y;
//comment the lines in start method which captures original_x and original_y
//this.original_x = Raphael.parseTransformString(this.attr("transform"))[0][1];
//this.original_y = Raphael.parseTransformString(this.attr("transform"))[0][2];
More info regarding tracking the co-ordinates:
We will have one more coordinate say updated_x and updated_y, which will be updated in the move method. onFinish/onUp method, we can have the check whether we should update the new position or not. Here, it just asks whether new position should be updated or not and based on our input, it sets the final result.
Check this fiddle:
this.start = function() {
if (this.reference.static) return;
//this.original_x = Raphael.parseTransformString(this.attr("transform"))[0][1];
//this.original_y = Raphael.parseTransformString(this.attr("transform"))[0][2];
this.animate({r: 70, opacity: 0.25}, 500, ">");
this.updated_x = this.original_x;
this.updated_y = this.original_y;
};
this.move = function(dx, dy) {
//var ts = Raphael.parseTransformString(this.attr("transform"));
this.updated_x = this.original_x + dx;
this.updated_y = this.original_y + dy;
//ts[0][1] = this.original_x + dx;
//ts[0][2] = this.original_y + dy;
this.attr({transform: 't' + this.updated_x + ',' + this.updated_y});
};
this.up = function() {
if(confirm("Shall I update the new position??")) {
this.original_x = this.updated_x;
this.original_y = this.updated_y;
}
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
this.attr({fill: "#fff"});
this.animate({r: 50, opacity: 1}, 500, ">");
};
I'm not quite sure why that problem happens yet, but I'm wondering if this may be a better solution anyway. Rather than parsing the strings each time, just store the transform and use that.
I've also switched it to use the transform() method, rather than the attr(transform:..) method. Whilst I think that would normally work, its not quite right logically, as SVG attributes don't take a Raphael transform string, but I assume Raph would intercept that and deal with it (but maybe more error prone).
Its also worth bearing in mind in a transform string that 't' is a relative transform and 'T' is an absolute transform (I don't think thats the issue as there's no preceding transform, but I was wondering if its also related).
this.start = function() {
if (this.reference.static) return;
this.original_t = this.transform();
this.animate({r: 70, opacity: 0.25}, 500, ">");
};
this.move = function(dx, dy) {
this.transform( this.original_t + 't' + dx + ',' + dy);
};
this.up = function() {
this.transform( this.original_t );
console.log("transformString: " + this.original_t);
console.log("transformAttrib: " + this.transform());
this.attr({fill: "#fff"});
this.animate({r: 50, opacity: 1}, 500, ">");
};
jsfiddle
Found an interesting fix: you can avoid the situation if you add an epsilon to both this.original_x and this.original_y. The problem seems to disappear if this.original_x and this.original_y are not exactly the same as the starting coordinates. Check out: http://jsfiddle.net/6ozsfdaf/13/
this.up = function() {
var ts;
this.original_x += 0.0000000001;
this.original_y += 0.0000000001;
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
console.log("transformString: " + transformString);
console.log("transformAttrib: " + this.attr("transform"));
this.attr({fill: "#fff"});
this.animate({r: 50, opacity: 1}, 500, ">");
};
EDIT
Found the problem. In Raphael, Raphael.parseTransformString()'s output is cached and reused. In your move() method, you modify the output of Raphael.parseTransformString(), and Raphael tries to use your modified array when you supply it with the same string. This happens when the first drag() event is registered. You ask it to parse the current place, and then update the output array of arrays with the new location. And then, way later, when this.up() is called, you supply the Raphael.parseTransformString() with the same string. Raphael then uses your modified array of arrays. This is the fixed fiddle: http://jsfiddle.net/6ozsfdaf/16/
And here is the code (use a new array of arrays to transform when moved each time):
this.move = function(dx, dy) {
var ts = [];
ts.push(new Array('t'));
ts[0][1] = this.original_x + dx;
ts[0][2] = this.original_y + dy;
this.attr({transform: ts.toString()});
};

Snap SVG: Dragging group doesn't update elements

JSFiddle here: JSFiddle
When dragging a group of objects, the individual objects' location attributes don't seem to be getting updated. This occurs whether I use the default drag() handler or define my own. Even the group BBox operation doesn't seem to update. Code:
var s = Snap("#svg");
var move = function (dx, dy, posx, posy) {
this.attr({
x: posx,
y: posy
});
//this.transform("t" + dx + "," + dy);
};
var block = s.rect(100, 100, 100, 100);
var circle = s.circle(100, 100, 50);
var group = s.g(block, circle);
//group.drag(move, function () {}, function () {});
group.drag();
//block.drag(move, function () {}, function () {});
//just a way to keep info coming w/o an interminable script
document.addEventListener('mousemove', function (e) {
bbox = block.getBBox();
block_x = block.attr("x");
block_y = block.attr("y");
gbbox = group.getBBox();
console.log("block is at " + block_x + "," + block_y,
" Block Bbbox is at " + bbox.x + "," + bbox.y,
" Group Bbbox is at " + gbbox.x + "," + gbbox.y);
}, false);
If I define only one object (say, a rect) and leave it out of a group, and pass my own "move" function to the call to drag, and include setting the "x" and "y" attributes explicitly, then that works. But if I include the rect in a group, then...I can't figure out how to do it, and I've tried a few ways (see the multiple commented-out lines showing things I've tried). I need to know where the rect sub-group element ends up after the drag, or at least the BBox of the whole group. Neither of these seem to be getting updated -- i.e. the console log I put in shows the same numbers forever, no matter where I move the object(s).
Can anyone help?
JSFiddle here: JSFiddle
I think this is because they are two different things, so they aren't actually interchangable.
The drag handler uses transforms. A transform doesn't affect any other attributes, its just an attribute on an element (in this case the group element).
getBBox will work in its current transform space, note this may be different to the clients (eg if the svg were zoomed in/out). So they are two slightly different methods, that do different things.
Use getBoundingClientRect if you need a bounding box relative to the client window. Use getBBox if you need a bounding box in the elements current coordinate space.
Code is using snap.svg.zpd as well, so zoom is possible. Problem is at onStopMove function. Events are fired when group is moved arround. In group is one circle(this.select('#main-inner-circle')) which does not have predefined location inside group. Im trying to get correct cx and cy of that inner circle after moving group.
self.onMove = function (dx, dy, ev, x, y) {
var clientX, clientY;
var tdx, tdy;
if ((typeof dx == 'object') && (dx.type == 'touchmove')) {
clientX = dx.changedTouches[0].clientX;
clientY = dx.changedTouches[0].clientY;
dx = clientX - this.data('ox');
dy = clientY - this.data('oy');
}
var snapInvMatrix = this.transform().diffMatrix.invert();
snapInvMatrix.e = snapInvMatrix.f = 0;
tdx = snapInvMatrix.x(dx, dy);
tdy = snapInvMatrix.y(dx, dy);
this.transform("t" + [tdx, tdy] + this.data('ot'));
}
self.onStartMove = function (x, y, ev) {
if ((typeof x == 'object') && (x.type == 'touchstart')) {
x.preventDefault();
this.data('ox', x.changedTouches[0].clientX);
this.data('oy', x.changedTouches[0].clientY);
}
this.data('ot', this.transform().local);
if (callbacks.onStartMove) {
callbacks.onStartMove();
}
}
self.onStopMove = function () {
var self = this.select('#main-inner-circle');
this.data('ot', this.transform().local);
//self.data('ot', self.transform().local);
console.log(self.getTransformedBBox());
console.log(this.getBBox());
//console.log($(self.node).offset().left - $(self.node).parent().offset().left);
var bBox = this.getBBox();
//var x = bBox.x + $(self.node).offset().left - $(self.node).parent().offset().left + self.getBBox().width / 2;
//var y = bBox.y + $(self.node).offset().top - $(self.node).parent().offset().top + self.getBBox().height / 2;
model.updateElementCoordinates(index, $(this.node).attr("rel"), { x: self.getTransformedBBox().cx, y: self.getTransformedBBox().cy });
if (callbacks.onStopMove) {
callbacks.onStopMove();
}
}
In order to post this question, I'd created the JSFiddle but left out the crucial snap.svg definitions...
<script src="http://snapsvg.io/assets/js/snap.svg-min.js"></script>
...with that, then indeed the group.getBBox() method actually works. However:
Apparently, using getBBox() is incredibly slow -- much slower than just accessing a "x" attribute of something like I was doing before grouping objects. All I know is that my code slows to a crawl if I use getBBox() (I have a lot of objects on the screen).
Further down in the same post mentioned earier ["Get coordinates of svg group on drag with snap.svg"1 recommended getBoundingClientRect(), which also works fine AND is fast enough! My new, working Fiddle showing all of these methods is here: New JSFiddle.
So, future users: use .node.getBoundingClientRect().

Categories