Capture event.clientX original value - javascript

var startT = Date.now();
var startX = event.clientX;
var startY = event.clientY;
var endT = startT;
console.log(startX+","+endX);
while (endT < startT + 100) {
endT = Date.now();
}
var endX = event.clientX;
var endY = event.clientY;
var distance = Math.sqrt(Math.pow((endX - startX), 2) + Math.pow((endY - startY), 2));
var velocity = distance/100;
console.log(endT - startT);
console.log(startX+","+endX);
from event listener
<script>window.onmousemove = showPara;</script>
I was trying to calculate the distance and velocity that mouse moved over a time interval, but the event.clintX or Y will keep changing while the event happens, so do startX and startY. So the distance and the velocity are both 0.
Is there any method that can capture the start coordinate at a constant value?

You can store initial values on the mousedown event. And then compare them on moousemove and on mouseup.

Related

Touchend will cancel on canvas and doesnt fires

I have a weird problem. I'm creating a test game.Which uses touch events and canvas.There is a ball that you can push it and when you release your finger it must go(something like angry birds).
I made that in mouse and it work correctly.I wanna make it on android. But it doesn't run.But when you use 2 finger it works correctly.
I'm sure the problem is here :
canvas.addEventListener("touchstart",function(event){
event.preventDefault();
if (event.touches[0].clientX >= x && event.touches[0].clientX <= x + (radius * 2) && event.touches[0].clientY >= y && event.touches[0].clientY <= y + (radius * 2)) {
dx = 0;
dy = 0;
isindrag = true;
oldx = x;
oldy = y;
}
});
canvas.addEventListener("touchmove", function (event) {
event.preventDefault();
if (isindrag) {
x = event.touches[0].clientX;
y = event.touches[0].clientY;
}
});
canvas.addEventListener("touchend", function (event) {
var touchX = event.touches[0].clientX;
var touchY = event.touches[0].clientY;
if (isindrag && touchX < canvas.width && touchY < canvas.height && touchX > 0 && touchY > 0) {
isindrag = false;
dx = -(x - oldx) / 30;
dy = -(y - oldy) / 30;
ismoving = true;
}
});
canvas.addEventListener("touchcancel", function(event){
event.preventDefault();
});
x : x of ball
y : y of ball
dx : Delta x of ball
dy : delta y of ball
radius : radius of ball
Can you help me?
The touches object of a touch event contains a collection of points currently on the screen. Now imagine that you put a single finger onto the surface and release it. This will trigger a touchend event but as the touches object just contains information on the active 'fingers', it will come up empty thus there is no clientX or clientY property to query. In a touchend event handler you need to use changedTouches instead of touches.
So try changing
var touchX = event.touches[0].clientX;
var touchY = event.touches[0].clientY;
to
var touchX = event.changedTouches[0].clientX;
var touchY = event.changedTouches[0].clientY;

move div towards mouse at same speed per second

I have created the following code to make the player move towards the mouse, JSFiddle
Code
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(event) {
mouseX = event.pageX;
mouseY = event.pageY;
});
$(function(){
var $map = $(".map");
var $player = $('.player');
var centerPlayerX = $player.offset().left + $player.width() / 2;
var centerPlayerY = $player.offset().top + $player.height() / 2;
var movingInterval;
$('.map').on('mousedown', function(event){
movingInterval = setInterval(function(){
var clickedPosX = mouseX,
clickedPosY = mouseY;
var currentMapPositionX = parseFloat($map.css("background-position-x"));
var currentMapPositionY = parseFloat($map.css("background-position-y"));
var moveMapX = currentMapPositionX - clickedPosX/100 + centerPlayerX/100;
var moveMapY = currentMapPositionY - clickedPosY/100 + centerPlayerY/100;
$map.css({ "background-position-x": `${moveMapX}px`, "background-position-y": `${moveMapY}px` });
var angle = getDirection(centerPlayerX, clickedPosY, clickedPosX, centerPlayerY);
$player.find('.ship').css('transform', 'rotate('+angle+'deg)');
}, 10);
}).on('mouseup', function() {
clearInterval(movingInterval);
});;
});
function getDirection(x1, y1, x2, y2){
var dx = x2 - x1;
var dy = y2 - y1;
return Math.atan2(dx, dy) / Math.PI * 180;
}
Problem
var moveMapX = currentMapPositionX - clickedPosX/100 + centerPlayerX/100;
var moveMapY = currentMapPositionY - clickedPosY/100 + centerPlayerY/100;
Problem is that I want to move the player at a set speed (px*ps). Currently the player will increase in speed when the player moves his mouse further away from the image. I currently have no idea on how I would move the player at a set speed. Therefore I would need to remove clickedPosY/X somehow and change it to a static speed but the image should still move towards were the mouse is, which is the problem.
So, let's assume you have a speed constant; what you want to do is to project the speed constant along the movement vector. The easiest way to do that is to scale the components of the offset to the click position by the ratio of the speed to the distance between the click point and the movement base:
var distanceX = clickedPosX - centerPlayerX;
var distanceY = clickedPosY - centerPlayerY;
var magnitude = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
var deltaX = distanceX * speed / magnitude;
var deltaY = distanceY * speed / magnitude;
var moveMapX = currentMapPositionX - deltaX;
var moveMapY = currentMapPositionY - deltaY;
Updated fiddle

How move the fake cursor randomly?

I want to have 2 fakes cursors, i tried this one for creating 2 cursors.
// get the fake cursor by is id
var xyMirror = document.getElementById('fakeCursor');
var xyMirror2 = document.getElementById('fakeCursor2');
// listen for mouse movements
window.onmousemove = function(event) {
// get the user's mouse position
var X = event.clientX;
var Y = event.clientY;
// get the browser window dimensions
windowHeight = window.innerHeight;
windowWidth = window.innerWidth;
// create an inversion of the mouse X, Y position
// subtract mouse X position from window width
// subtract mouse Y position from window height
var fakeX = windowWidth - X;
var fakeY = windowHeight - Y;
// use those numbers to update the fake cursor position
xyMirror.style.top = fakeY+'px';
xyMirror.style.left = fakeX+'px';
xyMirror2.style.top = 10 + fakeY+'px' ;
xyMirror2.style.left = 20 + fakeX+'px';
}
now their movement depend on original cursor,
my question is
How can move them randomly?
You can do some thing like that
// get the fake cursor by is id
var xyMirror = document.getElementById('fakeCursor');
var xyMirror2 = document.getElementById('fakeCursor2');
xyMirror.style.position = "absolute";
xyMirror2.style.position = "absolute";
var xMax = 0;var yMax = 0;
// listen for mouse movements
window.onmousemove = function(event) {
// Use event X and Y to set max value
if (event.clientX > xMax) xMax = event.clientX;
if (event.clientY > yMax) yMax = event.clientY;
// Random position for fakeCursor
xyMirror.style.left = getRandomArbitrary(0, xMax) +'px';
xyMirror.style.top = getRandomArbitrary(0, yMax)+'px';
// Random position for fakeCursor2
xyMirror2.style.left = getRandomArbitrary(0, xMax) +'px';
xyMirror2.style.top = getRandomArbitrary(0, yMax) +'px';
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
<div id="fakeCursor">fake1</div>
<div id="fakeCursor2">fake2</div>

How can canvas coordinates be converted into tile coordinates?

So I have a canvas with an isometric tile map drawn on it, which looks perfect.
In the event listener at the bottom of the script, I grab the cursor's coordinates inside the canvas. How could I find out which tile the cursor is hovering over?
var cs = document.getElementById('board');
var c = cs.getContext("2d")
var gridWidth=100
var gridHeight=50
var tilesX = 12, tilesY = 12;
var spriteWidth=gridWidth
var spriteHeight=img.height/img.width*gridWidth
cs.width = window.innerWidth //spriteWidth*10
cs.height = window.innerHeight //spriteHeight*10
var ox = cs.width/2-spriteWidth/2
var oy = (tilesY * gridHeight) / 2
window.onresize=function(){
cs.width = window.innerWidth //spriteWidth*10
cs.height = window.innerHeight //spriteHeight*10
ox = cs.width/2-spriteWidth/2
oy = (tilesY * gridHeight) / 2
draw()
}
draw();
function renderImage(x, y) {
c.drawImage(img, ox + (x - y) * spriteWidth/2, oy + (y + x) * gridHeight/2-(spriteHeight-gridHeight),spriteWidth,spriteHeight)
}
function draw(){
for(var x = 0; x < tilesX; x++) {
for(var y = 0; y < tilesY; y++) {
renderImage(x,y)
}
}
}
cs.addEventListener('mousemove', function(evt) {
var x = evt.clientX,
y = evt.clientY;
console.log('Mouse position: ' + x + ',' + y);
}, false);
Sorry for pasting such lengthy code, but all of it is there just to lay the isometric grid.
EDIT: Also, how could I get the top left coordinates of the tile image to relay it?
Assuming you've arranged your tiles where the leftmost column and topmost row are zero:
var column = parseInt(mouseX / tileWidth);
var row = parseInt(mouseY / tileHeight);
BTW, if you eventually move your canvas off the top-left of the page then you must adjust your mouse coordinates by the canvas offset.
Here's an example of how to calculate mouse position:
// references to the canvas element and its context
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// get the offset position of the canvas on the web page
var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;
// listen for mousedown events
canvas.onmousedown=handleMousedown;
function handleMousedown(e){
// tell the browser we will handle this event
e.preventDefault();
e.stopPropagation();
// calculate the mouse position
var mouseX=e.clientX-offsetX;
var mouseY=e.clientY-offsetY;
}

How do I make this function update the current mouse position?

I'm making a drawing pad, and I want the mouse location to update in an array as the mouse is dragged. Here is my code:
function penDown (x, y) {
isPenDown = true;
localPen.x = x;
localPen.y = y;
}
var X = [],
Y = [],
i = -1;
function penMove (x, y) {
if (isPenDown) {
++i;
X[i] = localPen.x;
Y[i] = localPen.y;
console.log("i is " + i + ", x is " + X[i] + ", y is " + Y[i]);
}
};
The console log shows that i is updating continuously when you move the mouse, but the X and Y coordinates of the mouse don't change - they just stay on the initial mouse location when you first press down the mouse.
Here is how I call penDown:
function pointerDownListener (e) {
// Retrieve a reference to the Event object for this mousedown event.
var event = e || window.event;
// Determine where the user clicked the mouse.
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// Move the drawing pen to the position that was clicked
penDown(mouseX, mouseY);
}
function pointerMoveListener (e) {
var event = e || window.event; // IE uses window.event, not e
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// Draw a line if the pen is down
penMove(mouseX, mouseY);
}
It might be, because your function penDown is only called once, so the values of x and y assigned to localPen won't change.

Categories