1
我有一個nodejs應用程序在當前使用for循環的畫布內創建網格。我需要幫助編寫一個算法來確定我的光標當前位於x和y明智的哪個單元格。網格目前是25x25,我正在跟蹤畫布內的鼠標移動。而不是給我一個原始的x和y鼠標座標,我想要一個單元座標。任何幫助?謝謝!確定一個畫布網格的單元格x和y
//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>
除法x/y座標由單元格的寬度/高度,然後向下取整以獲取單元座標 – weirdan