将鼠标移动的x和y坐标存储在文本文件中

时间:2019-06-10 15:46:28

标签: reactjs django-rest-framework react-fullstack

你好,我是全栈开发的新手,我要实现的目标是让我将这些x和y坐标由鼠标(光标)运动生成,我想将它们存储在本地的文本文件中/在服务器端。我应该怎么做?....我正在使用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);
            };

1 个答案:

答案 0 :(得分: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.