I have a nodejs application that creates a grid within a canvas currently using for loops. I need help writing an algorithm to determine which cell i my cursor is currently in x and y wise. The grid is currently 25x25 and I am tracking mouse movements within the canvas. Instead of giving me a raw x and y mouse coordinate I would like a cell coordinates. any help? thanks!
//START {EXPRESS}
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
//RETRIEVING THE MOUSE X AND Y COORDINATES
socket.on('mouseMove', function(data){
console.log(data.x + ", " + data.y);
});
});
<div id="gameDiv">
<center>
<canvas id="ctx" width="750" height="750" style="border:1px solid #000000;"></canvas>
</center>
</div>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
//NETWORK VARIABLES
var socket = io();
//GETTING THE CANVAS BY ID
var canvas = document.getElementById("ctx");
context = canvas.getContext("2d");
//GRID VARIABLES
var w=30,
h=30,
row=25,
col=25,
x=0,
y=0;
//LOOP TO DRAW THE GRID
for(x=0; x<row; x++){
for(y=0; y<col; y++){
context.strokeRect(w*x,h*y,w,h);
}
}
//GETTING THE MOUSE X AND Y
function getMousePos(canvas, event){
var rect = canvas.getBoundingClientRect();
return {
x:event.clientX - rect.left,
y:event.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(event){
var pos = getMousePos(canvas, event);
var posx = pos.x;
var posy = pos.y;
socket.emit('mouseMove',{x:x, y:y});
}, false);
</script>
</html>
via Jaekx
No comments:
Post a Comment