Based on the current code given and the requirements provided, here is the approach to render the trading drawable elements on the canvas using the Cup data from the useRustWsServer hook.
User
cup из useRustWsServer() обновляется постоянно, а
не перерисовывается, всегда один и тот же, отрисовалось и все
Assistant
Для обновления содержимого элемента canvas в реальном времени нужно использовать useRef для ссылки на элемент canvas и изменить useEffect, чтобы очистить и рисовать данные на элементе canvas при каждом обновлении данных.
Добавьте canvasRef с использованием useRef.
const canvasRef = useRef(null);
Измените useEffect так, чтобы использовать canvasRef.
useEffect(() => {
// Get the Canvas element and its Context
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d");
// Set up the dimensions for the canvas
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
// Clear the canvas before rendering the new data
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Define parameters for positioning the trading drawable elements on canvas
let xPos = canvas.width;
let yPos = rowHeight;
// Iterate over cup data and render the elements
for (let item of cup) {
xPos -= 50;
if (xPos < 0) {
xPos = canvas.width;
yPos += rowHeight;
}
renderCupItem(ctx, item, xPos, yPos, maxVolume);
}
}, [cup, maxVolume]);
User
не обновляется, хотя cup всегда обновляется
Assistant
Моя извинения за это недоразумение.
Давайте попробуем другой подход с использованием отдельного useEffect, чтобы отслеживать обновления данных cup и изменять состояние, за которое отвечает за принудительную перерисовку канваса.
Создайте новое состояние renderKey с помощью useState.
const [renderKey, setRenderKey] = useState(0);
Используйте отдельный useEffect следить за обновлениями cup, который изменяет состояние renderKey, что вызовет принудительную перерисовку canvas.
import {BestMicroPrice, useRustWsServer} from "../../hooks/rustWsServer";
import {createContext, Reducer, useEffect, useReducer, useRef, useState} from "react";
import CupDrawer from "../CupDrawer/CupDrawer";
import {IconButton} from "@mui/material";
import {AddRounded, RemoveRounded} from "@mui/icons-material";
import {ReadyState} from "../../enums/readyState";
import {useSelector} from "react-redux";
import {AppState} from "../../store/store";
В компоненте TradingCup запрашивается cup из useRustWsServer, сделать отрисовку канвас как в методах renderTrade renderTrades .
renderTrade renderTrades то другой немного компонент с немного другими данными, нужно использовать его в TradingCup только с нашими данными type CupItem = {
futures_price_micro: number;
quantity: number;
spot_quantity: number;
side: string;
};
В методе renderTrade() показатели quantity и price_float перемножаются, чтобы получить объем в $. Нам это не нужно, будем выводить только quantity.
Нужно все отрисовать в канвасе И использовать тоже самое соединение, что установлено в rustWsServer.ts
обязательно везде typescript
Import the required hooks, components, and utilities to TradingCup.tsx.
import { useRef, useEffect } from "react";
import { deepGreen, deepRed, rowHeight } from "../../constants/consts";
import { abbreviateNumber } from "../../utils/utils";
Add a new function 'renderCupItem' that will draw the elements in the canvas using the CupItem data.
const renderCupItem = (ctx, item, xPos, yPos, maxVolume) => {
const sizeRatio = item.quantity / maxVolume;
const bubbleSize = 35 * sizeRatio;
// Set the fill color and stroke color
const fillColor = item.side === "Sell" ? deepGreen : deepRed;
ctx.fillStyle = fillColor;
ctx.strokeStyle = "black";
// Draw the circle on the canvas
ctx.beginPath();
ctx.arc(xPos, yPos, bubbleSize, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
// Render the text
const labelText = abbreviateNumber(item.quantity);
const { width: textWidth } = ctx.measureText(labelText);
ctx.fillStyle = "#FFFFFF";
ctx.fillText(labelText, xPos - textWidth / 2, yPos + rowHeight / 2 - 2);
};
Create a new useEffect that sets up the rendering of cup data on the canvas whenever the data changes.
useEffect(() => {
// Get the Canvas element and it's Context
const canvas = document.getElementById("trading-canvas");
const ctx = canvas.getContext("2d");
// Set up the dimensions for the canvas
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
// Clear the canvas before rendering the new data
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Define parameters for positioning the trading drawable elements on canvas
let xPos = canvas.width;
let yPos = rowHeight;
// Iterate over cup data and render the elements
for (let item of cup) {
xPos -= 50;
if (xPos < 0) {
xPos = canvas.width;
yPos += rowHeight;
}
renderCupItem(ctx, item, xPos, yPos, maxVolume);
}
}, [cup, maxVolume]);
Add the canvas element to the TradingCup component with the id "trading-canvas".