0

您好,我是全栈开发的新手,我想要实现的是让我拥有这些由鼠标(光标)移动生成的 x 和 y 坐标,我想将其存储在本地/服务器上的文本文件中side.我应该怎么做呢?....我使用 react 作为我的前端并计划使用 Django 作为我的后端。

我可以使用 console.log() 查看不断更新的 x 和 y 坐标值……这是我的代码片段;

Container.onmousemove = function (e) {
                e.preventDefault();
                let x = e.layerX;
                let y = e.layerY;
                if (e.touches) {
                    x = e.touches[0].pageX;
                    y = e.touches[0].pageY;
                }
                //x & y coordinates of present cursor position
                  console.log(x,y);
            };
4

1 回答 1

0

由于看起来您正在触摸,因此这里用于触摸事件(移动)。如果您正在考虑桌面,请mouseOver改用。代码中包含一些注释,但本质上您可以在本地跟踪所有更改,但是您需要将数据发送到服务器以解析它并将其上传到文件。这最终可能会成为一个非常大的文件,因此请仔细检查一下,一旦您完成设置,它不会对性能产生太大影响!一种替代方法是使用浏览器的原生事件来代替 React 的工作。

客户

import React from 'react';

function Container({addTouch}) {
  const updateCoordinates = e => {
    e.stopPropagation();
    e.persist(); // React synthetic events are pooled if not
    // Can also use native event
    // For more on events check out:
    // https://reactjs.org/docs/events.html
    const {clientX: x,clientY: y} = e.touches[0];
    addTouch(e.timeStamp, {x: x | 0,y: y | 0}); // | 0 is Math.floor. Remove if you want exact px
    // Using the timestamp as a key, but keep track of them however
  }

  return (
    <div className="Container" onTouchMove={e=>updateCoordinates(e)}>
      Container
    </div>
  )
}

function App() {
  const touchList = new Map();
  const addTouch = (timestamp, coordinates) => touchList.set(timestamp, coordinates);
  const sendToServer = () => {
    // You could put this on an interval to that
    // sends the touch list and clears the map
    const url = '//yourUrl/yourEndPoint/';
    fetch(url, {
      method: 'POST', // or 'PUT'
      body: JSON.stringify([...touchList]),
      headers:{
        'Content-Type': 'application/json',
        // Include your credentials here depending on how your API is set up
      }
    }).then(res => res.json())
    .then(response => console.log('Success:', response)) // or stringify response if getting back data
    .catch(error => console.error('Error:', error));
  }
  return (
    <div className="App">
      <Container addTouch={addTouch}/>
      <button onClick={sendToServer}>SEND TOUCH LIST</button>
    </div>
  );
}

服务器

# Handle your parsing and saving on the server however
# This is basic python/django since not sure how your servers set up
# I remember the REST framework having some built in classes
# like a serializer to handle some of this stuff for you
# You can create your own model in models.py
# then just get the request data in views.py and use your model functions to handle

import csv

from django.http import HttpResponse # ,JsonResponse if you're sending the data back
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view

@api_view(['POST', 'PUT'])
def post_endpoint(request):
    """
    Save mouse coordinates to some file
    """
    # Might want to try, except request first before doing this

    if request.method == "POST":
        data = JSONParser().parse(request)
        filename = "touchList.csv"
        with open(filename, "a", newline='') as file:
            reader = csv.reader(file_obj, delimiter=',')
            fieldnames = ['timestamp', 'x', 'y'] # if using models you can define fields=(...)
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            for i in range(0, data.length): # or start at last file row
                writer.writerow({
                    'timestamp': data[i]['timestamp'],
                    'x': data[i]['x'],
                    'y': data[i]['y']
                })
        return HttpResponse('Success', status=201) # 201: Created, or 200, etc.

     # ...default response, error, etc.
于 2019-06-10T18:06:44.830 回答