gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
请给我写一个动态星空图的react组件
- User
请给我写一个动态星空图的react组件
- Assistant
当然,这里是一个简单的动态星空图的React组件示例。这个组件使用了Canvas来绘制动态星空效果:
import React, { useRef, useEffect } from 'react'; const DynamicStarfield = () => { const canvasRef = useRef(null); useEffect(() => { const canvas = canvasRef.current; const ctx = canvas.getContext('2d'); const stars = []; const numStars = 100; // 设置Canvas大小 const setCanvasSize = () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }; // 初始化星星的位置和速度 const initStars = () => { for (let i = 0; i < numStars; i++) { stars.push({ x: Math.random() * canvas.width, y: Math.random() * canvas.height, size: Math.random() * 1.5, speed: Math.random() * 0.5 }); } }; // 绘制星星 const drawStars = () => { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'white'; stars.forEach((star) => { ctx.beginPath(); ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2); ctx.fill(); }); }; // 更新星星的位置 const updateStars = () => { stars.forEach((star) => { star.y += star.speed; if (star.y > canvas.height) { star.y = 0; star.x = Math.random() * canvas.width; } }); }; // 动画循环 const animate = () => { updateStars(); drawStars(); requestAnimationFrame(animate); }; // 初始化画布和星星,并启动动画 setCanvasSize(); initStars(); animate(); // 处理窗口大小调整 window.addEventListener('resize', setCanvasSize); // 清理操作 return () => { window.removeEventListener('resize', setCanvasSize); }; }, []); return <canvas ref={canvasRef} style={{ display: 'block', background: 'black' }} />; }; export default DynamicStarfield;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.