Ich habe eine Nodejs-Anwendung, die ein Raster innerhalb einer Arbeitsfläche erstellt, die derzeit for-Schleifen verwendet. Ich brauche Hilfe beim Schreiben eines Algorithmus, um zu bestimmen, welche Zelle ich meinen Cursor derzeit in x und y weise bin. Das Raster ist derzeit 25x25 und ich verfolge Mausbewegungen innerhalb der Leinwand. Anstatt mir eine rohe X- und Y-Maus-Koordinate zu geben, möchte ich eine Zelle koordinieren. irgendeine Hilfe? Vielen Dank!Bestimmen der Zelle x und y eines Canvas-Gitters
//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){
\t //RETRIEVING THE MOUSE X AND Y COORDINATES
\t socket.on('mouseMove', function(data){
\t \t console.log(data.x + ", " + data.y);
\t });
});
<div id="gameDiv">
\t <center>
\t <canvas id="ctx" width="750" height="750" style="border:1px solid #000000;"></canvas>
\t </center>
</div>
\t
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
\t
<script>
\t //NETWORK VARIABLES
\t var socket = io();
\t //GETTING THE CANVAS BY ID
\t var canvas = document.getElementById("ctx");
\t context = canvas.getContext("2d");
\t
\t //GRID VARIABLES
\t var w=30,
\t h=30,
\t row=25,
\t col=25,
\t x=0,
\t y=0;
\t
\t //LOOP TO DRAW THE GRID
\t for(x=0; x<row; x++){
\t \t for(y=0; y<col; y++){
\t \t \t context.strokeRect(w*x,h*y,w,h);
\t \t }
\t }
\t
\t //GETTING THE MOUSE X AND Y
\t function getMousePos(canvas, event){
\t \t var rect = canvas.getBoundingClientRect();
\t \t return {
\t \t \t x:event.clientX - rect.left,
\t \t \t y:event.clientY - rect.top
\t \t };
\t }
\t
\t canvas.addEventListener('mousemove', function(event){
\t \t var pos = getMousePos(canvas, event);
\t \t var posx = pos.x;
\t \t var posy = pos.y;
\t \t
socket.emit('mouseMove',{x:x, y:y});
\t }, false);
\t
\t
\t
</script>
</html>
Dividieren x/y-Koordinaten, die durch Zell Breite/Höhe und dann runden Sie ab, um Zellkoordinaten zu erhalten – weirdan