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