xiaohongshu
xiaohongshu
drawing-canvas-implementation
Implement real-time collaborative drawing canvas with brush tools, color picker, undo/clear functionality, and canvas-to-image export. Use when building drawing UI, handling stroke synchronization, managing drawing state, or uploading drawings to storage.
Full skill instructions
This skill implements a full-featured Pictionary drawing canvas with real-time collaborative features, local drawing tools (brush, eraser, color picker), and integration with Convex file storage for drawing export and archival.
interface DrawingState {
strokes: Stroke[]; // Array of all strokes
currentStroke: Point[]; // Current drawing in progress
currentColor: string; // Hex color
currentSize: number; // Brush size in pixels
isErasing: boolean; // Eraser mode toggle
canUndo: boolean; // Undo availability
}
interface Stroke {
points: Point[]; // Array of coordinates
color: string; // Stroke color
size: number; // Brush size
isEraser: boolean; // Is eraser stroke
timestamp: number; // When drawn
}
interface Point {
x: number;
y: number;
pressure?: number; // Pen pressure (0-1) for tablets
}
Main canvas component with all drawing tools.
interface DrawingCanvasProps {
gameId: Id<"games">;
turnId: Id<"turns">;
isDrawer: boolean; // Can draw if true
onDrawingUpdate?: (strokes: Stroke[]) => void;
onDrawingComplete?: (imageUrl: string) => void;
timeLimit: number; // In seconds
}
// Mouse down - start stroke
canvas.addEventListener("mousedown", (e) => {
const point = getCanvasPoint(e);
currentStroke = [point];
drawPoint(point);
});
// Mouse move - continue stroke
canvas.addEventListener("mousemove", (e) => {
if (!isDrawing) return;
const point = getCanvasPoint(e);
currentStroke.push(point);
drawLine(currentStroke[currentStroke.length - 2], point);
});
// Mouse up - finish stroke
canvas.addEventListener("mouseup", (e) => {
if (currentStroke.length > 0) {
strokes.push({
points: currentStroke,
color: currentColor,
size: currentSize,
isEraser: isErasing,
timestamp: Date.now(),
});
}
currentStroke = [];
redrawCanvas();
});
canvas.addEventListener('touchstart', (e) => {
const touch = e.touches[0];
const point = getCanvasPoint(touch);
currentStroke = [point];
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
const touch = e.touches[0];
const point = getCanvasPoint(touch);
currentStroke.push(point);
drawLine(currentStroke[currentStroke.length - 2], point);
});
canvas.addEventListener('touchend', (e) => {
strokes.push({ points: currentStroke, ... });
currentStroke = [];
redrawCanvas();
});
function drawLine(from: Point, to: Point) {
ctx.strokeStyle = currentColor;
ctx.lineWidth = currentSize;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
}
function redrawCanvas() {
// Clear canvas
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Redraw all strokes
for (const stroke of strokes) {
ctx.strokeStyle = stroke.color;
ctx.lineWidth = stroke.size;
ctx.beginPath();
ctx.moveTo(stroke.points[0].x, stroke.points[0].y);
for (let i = 1; i < stroke.points.length; i++) {
ctx.lineTo(stroke.points[i].x, stroke.points[i].y);
}
ctx.stroke();
}
}
function captureCanvas(): Promise<Blob> {
return new Promise((resolve) => {
canvas.toBlob(
(blob) => {
resolve(blob!);
},
"image/png",
0.95
);
});
}
const uploadDrawing = useAction(
api.actions.uploadDrawing.uploadDrawingScreenshot
);
async function saveDrawing() {
const blob = await captureCanvas();
const storageId = await uploadDrawing({
gameId,
turnId,
drawingBlob: await blob.arrayBuffer(), // Base64 or buffer
});
return storageId; // Can fetch later with getUrl()
}
// On each stroke completion
const syncStrokes = useMutation(api.mutations.drawings.syncStrokes);
async function broadcastStroke(stroke: Stroke) {
await syncStrokes({
turn_id: turnId,
stroke: stroke,
});
}
const remoteStrokes = useQuery(api.queries.drawings.getTurnDrawing, {
turn_id: turnId,
});
// Subscribe to updates
useEffect(() => {
if (remoteStrokes?.strokes) {
redrawCanvas(); // Redraw with remote strokes
}
}, [remoteStrokes]);
export const DrawingCanvas = ({ isDrawer, ...props }: DrawingCanvasProps) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const [strokes, setStrokes] = useState<Stroke[]>([]);
const [currentColor, setCurrentColor] = useState("#000000");
const [currentSize, setCurrentSize] = useState(5);
const [isErasing, setIsErasing] = useState(false);
useEffect(() => {
if (!canvasRef.current) return;
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d")!;
// Event handlers...
// Canvas drawing logic...
}, [strokes, currentColor, currentSize, isErasing]);
const handleUndo = () => {
setStrokes(strokes.slice(0, -1));
};
const handleClear = () => {
if (confirm("Clear canvas?")) {
setStrokes([]);
}
};
return (
<div className="drawing-container">
<canvas
ref={canvasRef}
width={800}
height={600}
className="border-2 border-gray-300"
style={{ cursor: isDrawer ? "crosshair" : "default" }}
/>
<ToolBar
color={currentColor}
onColorChange={setCurrentColor}
size={currentSize}
onSizeChange={setCurrentSize}
isErasing={isErasing}
onEraserToggle={setIsErasing}
onUndo={handleUndo}
onClear={handleClear}
canUndo={strokes.length > 0}
/>
</div>
);
};
function resizeCanvas() {
const container = canvas.parentElement!;
const rect = container.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
redrawCanvas(); // Redraw at new size
}
window.addEventListener("resize", resizeCanvas);
.drawing-container {
aspect-ratio: 4 / 3;
width: 100%;
max-width: 800px;
}
canvas {
width: 100%;
height: 100%;
}
requestAnimationFrame for smooth drawingconst hasDrawn = strokes.length > 0;
useEffect(() => {
if (turnState === "completed") {
saveDrawing();
}
}, [turnState]);
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (strokes.length > 0) {
e.preventDefault();
e.returnValue = "";
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [strokes]);
components/game/drawing-canvas.tsx - Full component implementationcomponents/game/tool-bar.tsx - Tool controls UIxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience