Сохранять координаты x и y движений мыши в текстовом файле - PullRequest
0 голосов
/ 10 июня 2019

Здравствуйте, я новичок в разработке fullstack. Я пытаюсь добиться того, чтобы эти координаты x и y были сгенерированы движениями мыши (курсора), которые я хочу сохранить в текстовом файле локально/ на стороне сервера. Как мне это сделать? .... Я использую реагирование в качестве внешнего интерфейса и планирую использовать Django в качестве своего бэкенда.

Я вижу постоянно обновляемые значения x икоординаты y с использованием console.log () ... Вот мой фрагмент кода;

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 голосов
/ 10 июня 2019

Так как похоже, что вы делаете прикосновения, здесь для сенсорных событий (мобильных).Если вы думаете о настольном компьютере, используйте вместо этого 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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...