import {TradeItem} from “…/…/…/store/orderClusterSlice”; import {OrderFeedProps} from…
- User
import {TradeItem} from “…/…/…/store/orderClusterSlice”; import {OrderFeedProps} from “./OrderFeed.props”;
у меня в проекте идет отрисовка через canvasRef.current?.getContext("2d"); CanvasRenderingContext2D, нужно сделать отрисовку более производительнее на WebGL какая из библиотек на react будет самая быстрая и произвожительная
const OrderFeed = ({workerRef, symbol, settings}: OrderFeedProps) => {
const cupParams = useSelector((state: AppState) => state.cupSlice); const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio)); const [canvasSize, setCanvasSize] = useState({height: 0, width: 0}); const containerRef = useRef<HTMLDivElement|null>(null); const canvasRef = useRef<HTMLCanvasElement|null>(null); const theme = useTheme(); const draw = (trades: TradeItem[], camera: number) => { if (null === canvasRef || !Array.isArray(trades)) return;
const context = canvasRef.current?.getContext(“2d”);
if (context) {
orderFeedDrawer.clear(context, canvasSize); orderFeedDrawer.drawLine( context, canvasSize, trades, camera, cupParams.aggregatedPriceStep, cupParams.cellHeight, cupParams.quantityDivider, !settings.minQuantity ? 0 : parseFloat(settings.minQuantity), dpiScale, theme, ); orderFeedDrawer.drawChain( context, canvasSize, trades, camera, cupParams.aggregatedPriceStep, cupParams.cellHeight, cupParams.quantityDivider, cupParams.priceDivider, !settings.minQuantity ? 0 : parseFloat(settings.minQuantity), dpiScale, theme, settings.volumeAsDollars, ); } };
useEffect(() => { if (!workerRef.current) return; draw(event.data.trades, event.data.camera) }, [workerRef.current, canvasRef.current, canvasSize, symbol ]);
return <Box ref={containerRef} className={${styles.canvasWrapper} scroll-block}> ; };
export default OrderFeed;
const orderFeedDrawer = { clear: (ctx: WebGLRenderingContext, size: CanvasSize) => { ctx.clearRect(0, 0, size.width, size.height); }, drawLine: ( ctx: CanvasRenderingContext2D, canvasSize: CanvasSize, trades: TradeItem[], camera: number, aggregatedPriceStep: number, cupCellHeight: number, quantityDivider: number, minQuantity: number, dpiScale: number, theme: Theme, ) => { let startX = canvasSize.width - 10 * dpiScale; const fullHeightRowsCount = parseInt((canvasSize.height / cupCellHeight).toFixed(0)); const startY = (fullHeightRowsCount % 2 ? fullHeightRowsCount - 1 : fullHeightRowsCount) / 2 * cupCellHeight; const halfCupCellHeight = cupCellHeight / 2;
ctx.beginPath(); ctx.strokeStyle = orderFeedOptions(theme).line.color; ctx.lineWidth = (dpiScale) => 2 * dpiScale;
trades.forEach(trade => { const yModifier = (trade.price - (trade.price - (trade?.secondPrice || trade.price)) / 2 - camera) / aggregatedPriceStep * cupCellHeight + halfCupCellHeight; const width = 1.75 * clamp((trade.quantity / quantityDivider < minQuantity ? 0 : trade.radius), 5, 50) * dpiScale;
ctx.lineTo(startX - width / 2, startY - yModifier); startX = startX - width; });
- Assistant
На React есть несколько библиотек для работы с WebGL, которые могут помочь вам сделать отрисовку более производительной:
-
Three.js: Это одна из самых популярных библиотек для работы с 3D-графикой и WebGL. Она предоставляет множество инструментов и упрощает процесс создания сложных визуализаций. Three.js также имеет хорошую документацию и активную сообщество пользователей.
-
React-Three-Fiber: Это надстройка над Three.js, которая позволяет использовать Three.js в React-приложениях с помощью декларативного подхода. React-Three-Fiber добавляет свойства, компоненты и хуки React к Three.js, чтобы сделать код более понятным и упрощенным.
-
regl: Это библиотека для работы с WebGL, оптимизированная для производительности. Она предоставляет низкоуровневый интерфейс для исключения накладных расходов и улучшения производительности рендеринга. regl также позволяет вам использовать GLSL (язык шейдеров) для создания пользовательских шейдерных программ.
-
- User
перепиши код по библиотеке regl
- Assistant
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.